summaryrefslogtreecommitdiffstats
path: root/chrome/common/extensions/docs/static/background_pages.html
blob: 78bf836674d491023c3150bc6d560627d80bdb4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<div id="pageData-title" class="pageData">Background Pages</div>
<div id="pageData-showTOC" class="pageData">true</div>

<p>
A common need for extensions is to have
a single long-running script to manage some task or state.
Toolstrips don't quite fit this need,
because multiple toolstrips can be active at any one time
(one per browser window).
Background pages to the rescue.
</p>

<p>
The background page is similar to a toolstrip,
in that it is an HTML page that runs in the extension process.
The difference is that the background page exists
for the lifetime of your extension,
and only one instance of it at a time is active.
</p>

<p>
In a typical extension with a background page,
the UI &mdash;
toolstrips, page actions, and so on &mdash;
is implemented with dumb views.
When the view needs some state,
it requests the state from the background page.
When the background page notices a state change,
the background page tells the views to update.
</p>

<h2 id="manifest">Manifest</h2>

<p>
Register your background page in the extension manifest, like this:
</p>

<pre>{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  <b>"background_page": "background.html",</b>
  "toolstrips": ["toolstrip.html"]
}</pre>

<h2>Details</h2>

<p>
Your toolstrip will likely contain
only the necessary code to display the toolstrip UI,
with all your extension logic contained in the background page.
You can communicate between your various pages using direct script calls,
similar to how frames can communicate.
The chrome.extension.getViews() function
returns a list of window objects
for every active page belonging to your extension.
</p>

<h2>Example</h2>

<pre>background_page.html (snippet):
  function updateUI(checked) {
    var views = chrome.extension.getViews();
    for (var i in views) {
      if (views[i].enableCheckbox)
        views[i].enableCheckbox(checked);
    }
  }

toolstrip.html (snippet):
  function enableCheckbox(checked) {
    var elm = document.getElementById('checkbox');
    elm.checked = checked;
  }</pre>