aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.html
blob: e1b58780105dff2911030d5933a6e829399e3a19 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
---
title: Working with the Tabs API
slug: Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API
tags:
  - 选项卡
  - 附加组件
translation_of: Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API
---
<p>{{AddonSidebar}}</p>

<p><span class="tlid-translation translation" lang="zh-CN"><span title="">选项卡允许用户在其浏览器窗口中打开多个网页,然后在这些网页之间切换。</span> <span title="">使用Tabs API,您可以使用和操作这些选项卡来创建实用程序,为用户提供使用选项卡或提供扩展功能的新方法。</span></span></p>

<p>在这篇how-to文章中我们将看到:</p>

<ul>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">使用Tabs API所需的权限。</span></span></li>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">使用{{WebExtAPIRef("tabs.query")}}发现有关标签及其属性的更多信息。</span></span></li>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">创建、复制、移动、更新、重新加载和删除选项卡。</span></span></li>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">操纵标签的缩放大小。</span></span></li>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">操纵选项卡的CSS。</span></span></li>
</ul>

<p><span class="tlid-translation translation" lang="zh-CN"><span title="">最后,我们通过查看API提供的其他一些其他功能。</span></span></p>

<div class="blockIndicator note">
<p><span class="tlid-translation translation" lang="zh-CN"><span title="">注意:其他地方有一些Tab API功能。</span> <span title="">这些是可用于使用脚本操作选项卡内容的方法{{WebExtAPIRef("tabs.connect")}},{{WebExtAPIRef("tabs.sendMessage")}}和{{WebExtAPIRef("tabs.executeScript")}}</span><span title="">如果您需要有关这些方法的更多信息,请参阅概念文章<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">内容脚本</a>和操作指南<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page">修改网页</a></span></span></p>
</div>

<h2 id="权限和选项卡API"><span class="tlid-translation translation" lang="zh-CN"><span title="">权限和选项卡API</span></span></h2>

<p><span class="tlid-translation translation" lang="zh-CN"><span title="">对于大多数Tabs API函数,您不需要任何权限;</span> <span title="">但是,有一些例外:</span></span></p>

<ul>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">需要</span></span><code>"tabs"</code><span class="tlid-translation translation" lang="zh-CN"><span title="">权限才能访问Tab对象的<code>Tab.url</code><code>Tab.title</code><code>Tab.favIconUrl</code>属性。</span> <span title="">在Firefox中,您还需要</span></span><code>"tabs"</code><span class="tlid-translation translation" lang="zh-CN"><span title="">来按URL执行<a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query">查询</a></span></span></li>
 <li>{{WebExtAPIRef("tabs.executeScript")}}或{{WebExtAPIRef("tabs.insertCSS")}}需要<a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">主机权限</a></li>
</ul>

<p>以下是您可以在扩展程序的manifest.json文件中请求<code>"tabs"</code>权限的方法:</p>

<pre class="brush: json">"permissions": [
  "&lt;all_urls&gt;",
  "tabs"
],
</pre>

<p>此请求允许您在用户访问的所有网站上使用所有标签API功能。 还有一种替代方法可以请求权限使用{{WebExtAPIRef("tabs.executeScript")}}或{{WebExtAPIRef("tabs.insertCSS")}},其中您不需要主机权限,形式为<a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission"><code>"activeTab"</code></a>。 此权限与<code>&lt;all_urls&gt;</code>提供与<code>"tabs"</code>相同的权限,但有两个限制:</p>

<ul>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">用户必须通过其浏览器或页面操作,上下文菜单或快捷键与扩展进行交互。</span></span></li>
 <li><span class="tlid-translation translation" lang="zh-CN"><span title="">它仅在活动选项卡中授予权限。</span></span></li>
</ul>

<p><span class="tlid-translation translation" lang="zh-CN"><span title="">这种方法的好处是用户不会收到权限警告,也就是说您的扩展程序可以“访问所有网站的数据”。</span> <span title="">这是因为</span></span><code>&lt;all_urls&gt;</code><span class="tlid-translation translation" lang="zh-CN"><span title="">权限使扩展能够在任何选项卡中随时执行脚本,而</span></span><a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission"><code>"activeTab"</code></a><span class="tlid-translation translation" lang="zh-CN"><span title="">仅限于允许扩展在当前选项卡中执行用户请求的操作。</span></span></p>

<h2 id="Discovering_more_about_tabs_and_their_properties">Discovering more about tabs and their properties</h2>

<p>There will be occasions when you want to get a list of all the tabs in all the browser windows. Other times you might want to find a subset of tabs that match some specific criteria, such as those opened from a specific tab or displaying pages from a particular domain. And once you have your list of tabs, you’ll probably want to know more about their properties.</p>

<p>This is where {{WebExtAPIRef("tabs.query")}} comes in. Used alone to get all tabs or taking the <code>queryInfo</code> object—to specify query criteria such as whether the tab is active, in the current window, or one or more of 17 criteria—{{WebExtAPIRef("tabs.query")}} returns an array of {{WebExtAPIRef("tabs.Tab")}} objects containing information about the tabs.</p>

<p>Where you want information about the current tab only, you can get a {{WebExtAPIRef("tabs.Tab")}} object for that tab using {{WebExtAPIRef("tabs.getCurrent")}}. If you have a tab’s ID, you can get its {{WebExtAPIRef("tabs.Tab")}} object using {{WebExtAPIRef("tabs.get")}}.</p>

<div class="blockIndicator note">
<p><strong>Note:</strong></p>

<ul>
 <li><strong>In Chrome,</strong> the user can select multiple tabs in a window, and the Tabs API sees these as highlighted tabs.</li>
 <li><strong>In Firefox,</strong> the user can’t select multiple tabs, so “highlighted” and “active” are synonymous.</li>
</ul>
</div>

<h3 id="How_to_example">How to example</h3>

<p>To see how {{WebExtAPIRef("tabs.query")}} and {{WebExtAPIRef("tabs.Tab")}} are used, let’s walk through how the <a href="https://github.com/mdn/webextensions-examples/tree/master/tabs-tabs-tabs">tabs-tabs-tabs</a> example adds the list of “switch to tabs” to its toolbar button popup.</p>

<p><img alt="The tabs tabs tabs toolbar menu showing the switch to tap area" src="https://mdn.mozillademos.org/files/15723/Switch_to_tab.png" style="height: 645px; width: 369px;"></p>

<h3 id="manifest.json">manifest.json</h3>

<p>Here is the <a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/manifest.json">manifest.json</a>:</p>

<pre class="brush: json">{
  "browser_action": {
    "browser_style": true,
    "default_title": "Tabs, tabs, tabs",
    "default_popup": "tabs.html"
  },
  "description": "A list of methods you can perform on a tab.",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/tabs-tabs-tabs",
  "manifest_version": 2,
  "name": "Tabs, tabs, tabs",
  "permissions": [
    "tabs"
  ],
  "version": "1.0"
}
</pre>

<div class="blockIndicator note">
<p>Note the following:</p>

<ul>
 <li>
  <p><strong>tabs.html is defined as the <code>default_popup</code> in <code>browser_action</code>.</strong> It is displayed whenever the user clicks the extension’s toolbar icon.</p>
 </li>
 <li>
  <p><strong>Permissions includes tabs.</strong> This is needed to support the tab list feature, as the extension reads the title of the tabs for display in the popup.</p>
 </li>
</ul>
</div>

<h3 id="tabs.html">tabs.html</h3>

<p>tabs.html defines the content of the extension’s popup:</p>

<pre class="brush: html">&lt;!DOCTYPE html&gt;

&lt;html&gt;

 &lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;link rel="stylesheet" href="tabs.css"/&gt;
 &lt;/head&gt;

&lt;body&gt;

 &lt;div class="panel"&gt;
    &lt;div class="panel-section panel-section-header"&gt;
     &lt;div class="text-section-header"&gt;Tabs-tabs-tabs&lt;/div&gt;
    &lt;/div&gt;

    &lt;a href="#" id="tabs-move-beginning"&gt;Move active tab to the beginning of the window&lt;/a&gt;&lt;br&gt;


…

Define the other menu items
…

    &lt;div class="switch-tabs"&gt;

     &lt;p&gt;Switch to tab&lt;/p&gt;

     &lt;div id="tabs-list"&gt;&lt;/div&gt;

    &lt;/div&gt;
 &lt;/div&gt;

 &lt;script src="tabs.js"&gt;&lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;
</pre>

<p>Here is a summary of the above does:</p>

<ol>
 <li>The menu items are declared.  </li>
 <li>An empty <code>div</code> with the ID <code>tabs-list</code> is declared to contain the list of tabs.</li>
 <li>tabs.js is called.</li>
</ol>

<h3 id="tabs.js">tabs.js</h3>

<p>In <a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.js">tabs.js</a>, we’ll see how the list of tabs is built and added to the popup.  </p>

<h4 id="Creating_the_popup">Creating the popup</h4>

<p>First, an event handler is added to execute <code>listTabs()</code> when tabs.html is loaded:</p>

<pre class="brush: js">document.addEventListener("DOMContentLoaded", listTabs);</pre>

<p>The first thing that <code>listTabs()</code> does is to call <code>getCurrentWindowTabs()</code>. This is where {{WebExtAPIRef("tabs.query")}} is used to get a {{WebExtAPIRef("tabs.Tab")}} object for the tabs in the current window:</p>

<pre class="brush: js">function getCurrentWindowTabs() {
  return browser.tabs.query({currentWindow: true});
}
</pre>

<p>Now, <code>listTabs()</code> is ready to create the content for the popup.</p>

<p>To start with:</p>

<ol>
 <li>Grab the <code>tabs-list</code> <code>div</code>.</li>
 <li>Create a document fragment (into which the list will be built).</li>
 <li>Set counters.</li>
 <li>Clear the content of the <code>tabs-list</code> <code>div</code>.</li>
</ol>

<pre class="brush: js">function listTabs() {
 getCurrentWindowTabs().then((tabs) =&gt; {
    let tabsList = document.getElementById('tabs-list');
    let currentTabs = document.createDocumentFragment();
    let limit = 5;
    let counter = 0;

    tabsList.textContent = '';
</pre>

<p>Next, we’ll create the links for each tab:</p>

<ol>
 <li>Loops through the first 5 items from the {{WebExtAPIRef("tabs.Tab")}} object.</li>
 <li>For each item, add a hyperlink to the document fragment.
  <ul>
   <li>The link’s label—that is, its text—is set using the tab’s title (or the ID, if it has no title).</li>
   <li>The link’s address is set using the tab’s ID.</li>
  </ul>
 </li>
</ol>

<pre class="brush: js">    for (let tab of tabs) {
     if (!tab.active &amp;&amp; counter &lt;= limit) {
        let tabLink = document.createElement('a');

        tabLink.textContent = tab.title || tab.id;

       tabLink.setAttribute('href', tab.id);
        tabLink.classList.add('switch-tabs');
        currentTabs.appendChild(tabLink);
     }

     counter += 1;

    }
</pre>

<p>Finally, the document fragment is written to the <code>tabs-list</code> div:</p>

<pre class="brush: js">    tabsList.appendChild(currentTabs);
  });
}
</pre>

<h4 id="Working_with_the_active_tab">Working with the active tab</h4>

<p>Another related example feature is the “Alert active tab” info option that dumps all the {{WebExtAPIRef("tabs.Tab")}} object properties for the active tab into an alert:</p>

<pre class="brush: js"> else if (e.target.id === "tabs-alertinfo") {
   callOnActiveTab((tab) =&gt; {
     let props = "";
     for (let item in tab) {
       props += `${ item } = ${ tab[item] } \n`;
     }
     alert(props);
   });
 }
</pre>

<p>Where <code>callOnActiveTab()</code> finds the active tab object by looping through the {{WebExtAPIRef("tabs.Tab")}} objects looking for the item with active set:</p>

<pre class="brush: js">document.addEventListener("click", function(e) {
 function callOnActiveTab(callback) {
   getCurrentWindowTabs().then((tabs) =&gt; {
     for (var tab of tabs) {
       if (tab.active) {
         callback(tab, tabs);
       }
     }
   });
 }
}

</pre>

<h2 id="Creating_duplicating_moving_updating_reloading_and_removing_tabs">Creating, duplicating, moving, updating, reloading, and removing tabs</h2>

<p>Having gathered information about the tabs you’ll most likely want to do something with them—either to offer users features for manipulating and managing tabs or to implement functionality in your extension.</p>

<p>The following functions are available:</p>

<ul>
 <li>create a new tab ({{WebExtAPIRef("tabs.create")}}).</li>
 <li>duplicate a tab ({{WebExtAPIRef("tabs.duplicate")}}).</li>
 <li>remove a tab ({{WebExtAPIRef("tabs.remove")}}).</li>
 <li>move a tab ({{WebExtAPIRef("tabs.move")}}).</li>
 <li>update the tab’s URL—effectively browse to a new page—({{WebExtAPIRef("tabs.update")}}).</li>
 <li>reload the tab’s page ({{WebExtAPIRef("tabs.reload")}}).</li>
</ul>

<div class="blockIndicator note">
<p><strong>NOTE: </strong></p>

<p>These functions all require the ID (or IDs) of the tab they are manipulating:</p>

<ul>
 <li>{{WebExtAPIRef("tabs.duplicate")}}</li>
 <li>{{WebExtAPIRef("tabs.remove")}}</li>
 <li>{{WebExtAPIRef("tabs.move")}}</li>
</ul>

<p>Whereas the following functions will act on the active tab (if no tab ID is provided): </p>

<ul>
 <li>{{WebExtAPIRef("tabs.update")}}</li>
 <li>{{WebExtAPIRef("tabs.reload")}}</li>
</ul>
</div>

<h3 id="How_to_example_2">How to example</h3>

<p>The <a href="https://github.com/mdn/webextensions-examples/tree/master/tabs-tabs-tabs">tabs-tabs-tabs</a> example exercises all of these features except for updating a tab’s URL The way in which these APIs are used is similar, so we’ll look at one of the more involved implementations, that of the “Move active tab to the beginning of the window list” option.</p>

<p>But first, here is a demonstration of the feature in action:</p>

<p>{{EmbedYouTube("-lJRzTIvhxo")}}</p>

<h4 id="manifest.json_2"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/manifest.json">manifest.json</a></h4>

<p>None of the functions require a permission to operate, so there are no features in the manifest.json file that need to be highlighted.</p>

<h4 id="tabs.html_2"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.html">tabs.html</a></h4>

<p>tabs.html defines the “menu” displayed in the popup, which includes the “Move active tab to the beginning of the window list” option, with a series of <code>&lt;a&gt;</code> tags grouped by a visual separator. Each menu item is given an ID, which is used in tabs.js to determine which menu item is being requested.</p>

<pre class="brush: html">    &lt;a href="#" id="tabs-move-beginning"&gt;Move active tab to the beginning of the window&lt;/a&gt;&lt;br&gt;
    &lt;a href="#" id="tabs-move-end"&gt;Move active tab to the end of the window&lt;/a&gt;&lt;br&gt;

    &lt;div class="panel-section-separator"&gt;&lt;/div&gt;


    &lt;a href="#" id="tabs-duplicate"&gt;Duplicate active tab&lt;/a&gt;&lt;br&gt;

    &lt;a href="#" id="tabs-reload"&gt;Reload active tab&lt;/a&gt;&lt;br&gt;
    &lt;a href="#" id="tabs-alertinfo"&gt;Alert active tab info&lt;/a&gt;&lt;br&gt;</pre>

<h4 id="tabs.js_2"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.js">tabs.js</a></h4>

<p>To implement the “menu” defined in tabs.html, tabs.js includes a listener for clicks in tabs.html:</p>

<pre class="brush: js">document.addEventListener("click", function(e) {
 function callOnActiveTab(callback) {

   getCurrentWindowTabs().then((tabs) =&gt; {
     for (var tab of tabs) {
       if (tab.active) {
         callback(tab, tabs);
       }
     }
   });
}
}
</pre>

<p>A series of <code>if</code> statements then look to match the ID of the item clicked.</p>

<p>This code snippet is for the “Move active tab to the beginning of the window list” option:</p>

<pre class="brush: js"> if (e.target.id === "tabs-move-beginning") {
   callOnActiveTab((tab, tabs) =&gt; {
     var index = 0;
     if (!tab.pinned) {
       index = firstUnpinnedTab(tabs);
     }
     console.log(`moving ${tab.id} to ${index}`)
     browser.tabs.move([tab.id], {index});
   });
 }
</pre>

<p>It's worth noting the use of <code>console.log()</code>. This enables you to output information to the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging">debugger</a> console, which can be useful when resolving issues found during development.</p>

<p><img alt="Example of the console.log output, from the move tabs feature, in the debugging console" src="https://mdn.mozillademos.org/files/15722/console.png" style="height: 329px; width: 911px;"></p>

<p>The move code first calls <code>callOnActiveTab()</code> which in turn calls <code>getCurrentWindowTabs()</code> to get a {{WebExtAPIRef("tabs.Tab")}} object containing the active window’s tabs. It then loops through the object to find and return the active tab object:</p>

<pre class="brush: js"> function callOnActiveTab(callback) {
   getCurrentWindowTabs().then((tabs) =&gt; {
     for (var tab of tabs) {
       if (tab.active) {
         callback(tab, tabs);
       }
     }
   });
 }
</pre>

<h5 id="Pinned_tabs">Pinned tabs</h5>

<p>A feature of tabs is that the user can <dfn>pin</dfn> tabs in a window. Pinned tabs are placed at the start of the tab list and cannot be moved. This means that the earliest position a tab can move to is the first position after any pinned tabs. So, <code>firstUnpinnedTab()</code> is called to find the position of the first unpinned tab by looping through the <code>tabs</code> object:</p>

<pre class="brush: js">function firstUnpinnedTab(tabs) {
 for (var tab of tabs) {
   if (!tab.pinned) {
     return tab.index;
   }
 }
}
</pre>

<p>We now have everything needed to move the tab: the active tab object from which we can get the tab ID and the position the tab is to be moved to. So, we can implement the move:</p>

<pre class="brush: js">     browser.tabs.move([tab.id], {index});</pre>

<p>The remaining functions to duplicate, reload, create, and remove tabs are implemented similarly.</p>

<h2 id="Manipulating_a_tab’s_zoom_level">Manipulating a tab’s zoom level</h2>

<p>The next set of functions enable you to get ({{WebExtAPIRef("tabs.getZoom")}}) and set ({{WebExtAPIRef("tabs.setZoom")}}) the zoom level within a tab. You can also retrieve the zoom settings ({{WebExtAPIRef("tabs.getZoomSettings")}}) but, at the time of writing, the ability to set the settings ({{WebExtAPIRef("tabs.setZoomSettings")}}) wasn’t available in Firefox.</p>

<p>The level of zoom can be between 30% and 300% (represented as decimals <code>0.3</code> to <code>3</code>).</p>

<p>In Firefox the default zoom settings are:</p>

<ul>
 <li><strong>default zoom level: </strong>100%.</li>
 <li><strong>zoom mode:</strong> automatic (so the browser manages how zoom levels are set).</li>
 <li><strong>scope of zoom changes:</strong> <code>"per-origin"</code>, meaning that when you visit a site again, it takes the zoom level set in your last visit.</li>
</ul>

<h3 id="How_to_example_3">How to example</h3>

<p>The <a href="https://github.com/mdn/webextensions-examples/tree/master/tabs-tabs-tabs">tabs-tabs-tabs</a> example includes three demonstrations of the zoom feature: zoom in, zoom out, and reset zoom. Here is the feature in action:</p>

<p>{{EmbedYouTube("RFr3oYBCg28")}}</p>

<p>Let’s take a look at how the zoom in is implemented.</p>

<h4 id="manifest.json_3"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/manifest.json">manifest.json</a></h4>

<p>None of the zoom functions require permissions, so there are no features in the manifest.json file that need to be highlighted.</p>

<h4 id="tabs.html_3"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.html">tabs.html</a></h4>

<p>We have already discussed how the tabs.html defines the options for this extension, nothing new or unique is done to provide the zoom options.</p>

<h4 id="tabs.js_3"><a href="https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.js">tabs.js</a></h4>

<p>tabs.js starts by defining several constants used in the zoom code:</p>

<pre class="brush: js">const ZOOM_INCREMENT = 0.2;
const MAX_ZOOM = 3;
const MIN_ZOOM = 0.3;
const DEFAULT_ZOOM = 1;
</pre>

<p>It then uses the same listener we discussed earlier so it can act on clicks in tabs.html.</p>

<p>For the zoom in feature, this runs:</p>

<pre class="brush: js"> else if (e.target.id === "tabs-add-zoom") {
   callOnActiveTab((tab) =&gt; {
     var gettingZoom = browser.tabs.getZoom(tab.id);
     gettingZoom.then((zoomFactor) =&gt; {
       //the maximum zoomFactor is 3, it can't go higher
       if (zoomFactor &gt;= MAX_ZOOM) {
         alert("Tab zoom factor is already at max!");
       } else {
         var newZoomFactor = zoomFactor + ZOOM_INCREMENT;
         //if the newZoomFactor is set to higher than the max accepted
         //it won't change, and will never alert that it's at maximum
         newZoomFactor = newZoomFactor &gt; MAX_ZOOM ? MAX_ZOOM : newZoomFactor;
         browser.tabs.setZoom(tab.id, newZoomFactor);
       }
     });
   });
 }
</pre>

<p>This code uses <code>callOnActiveTab()</code> to get the details of the active tab, then {{WebExtAPIRef("tabs.getZoom")}} gets the tab’s current zoom factor. The current zoom is compared to the defined maximum (<code>MAX_ZOOM</code>) and an alert issued if the tab is already at the maximum zoom. Otherwise, the zoom level is incremented but limited to the maximum zoom, then the zoom is set with {{WebExtAPIRef("tabs.getZoom")}}.</p>

<h2 id="Manipulating_a_tab’s_CSS">Manipulating a tab’s CSS</h2>

<p>Another significant capability offered by the Tabs API is the ability to manipulate the CSS within a tab—add new CSS to a tab ({{WebExtAPIRef("tabs.insertCSS")}}) or remove CSS from a tab ({{WebExtAPIRef("tabs.removeCSS")}}).</p>

<p>This can be useful, for example, if you want to highlight certain page elements or change the default layout of the page.</p>

<h3 id="How_to_example_4">How to example</h3>

<p>The <a href="https://github.com/mdn/webextensions-examples/tree/master/apply-css">apply-css</a> example uses these features to add a red border to the web page in the active tab. Here is the feature in action:</p>

<p>{{EmbedYouTube("bcK-GT2Dyhs")}}</p>

<p>Let’s walk through how it’s set up.</p>

<h4 id="manifest.json_4"><a href="https://github.com/mdn/webextensions-examples/blob/master/apply-css/manifest.json">manifest.json</a></h4>

<p>To use the CSS features you need either:</p>

<ul>
 <li><code>"tabs"</code> permission and <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission</a> or</li>
 <li><code>"activeTab"</code> permission.</li>
</ul>

<p>The latter is the most useful, as it allows an extension to use {{WebExtAPIRef("tabs.insertCSS")}} and {{WebExtAPIRef("tabs.removeCSS")}} in the active tab when run from the extension’s browser or page action, context menu, or a shortcut.</p>

<pre class="brush: json">{
  "description": "Adds a page action to toggle applying CSS to pages.",

 "manifest_version": 2,
 "name": "apply-css",
 "version": "1.0",
 "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/apply-css",

 "background": {

    "scripts": ["background.js"]
 },

 "page_action": {

    "default_icon": "icons/off.svg",
    "browser_style": true
 },

 "permissions": [
    "activeTab",
    "tabs"
 ]

}
</pre>

<p>You will note that <code>"tabs"</code> permission is requested in addition to <code>"activeTab"</code>. This additional permission is needed to enable the extension’s script to access the tab’s URL, the importance of which we’ll see in a moment.</p>

<p>The other main features in the manifest.json file are the definition of:</p>

<ul>
 <li><strong>a background script</strong>, which starts running as soon as the extension is loaded.</li>
 <li><strong>a “page action”</strong>, which defines an icon to be added to the browser’s address bar.</li>
</ul>

<h4 id="background.js"><a href="https://github.com/mdn/webextensions-examples/blob/master/apply-css/background.js">background.js</a></h4>

<p>On startup, background.js sets some constants to define the CSS to be applied, titles for the “page action”, and a list of protocols the extension will work in:</p>

<pre class="brush: js">const CSS = "body { border: 20px solid red; }";
const TITLE_APPLY = "Apply CSS";
const TITLE_REMOVE = "Remove CSS";
const APPLICABLE_PROTOCOLS = ["http:", "https:"];
</pre>

<p>When first loaded, the extension uses {{WebExtAPIRef("tabs.query")}} to get a list of all the tabs in the current browser window. It then loops through the tabs calling <code>initializePageAction()</code>.</p>

<pre class="brush: js">var gettingAllTabs = browser.tabs.query({});

gettingAllTabs.then((tabs) =&gt; {
 for (let tab of tabs) {
   initializePageAction(tab);
 }
});
</pre>

<p><code>initializePageAction</code> uses <code>protocolIsApplicable()</code> to determine whether the active tab’s URL is one the CSS can be applied to:</p>

<pre class="brush: js">function protocolIsApplicable(url) {
 var anchor =  document.createElement('a');
 anchor.href = url;
 return APPLICABLE_PROTOCOLS.includes(anchor.protocol);
}
</pre>

<p>Then, if the example can act on the tab, <code>initializePageAction()</code> sets the tab’s <code>pageAction</code> (navigation bar) icon and title to use the “off” versions before making the <code>pageAction</code> visible:</p>

<pre class="brush: js">function initializePageAction(tab) {

 if (protocolIsApplicable(tab.url)) {
   browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
   browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
   browser.pageAction.show(tab.id);
 }
}
</pre>

<p>Next, a listener on <code>pageAction.onClicked</code> waits for the <code>pageAction</code> icon to be clicked, and calls <code>toggleCSS</code> when it is.</p>

<pre class="brush: js">browser.pageAction.onClicked.addListener(toggleCSS);</pre>

<p><code>toggleCSS()</code> gets the title of the <code>pageAction</code> and then takes the action described:</p>

<ul>
 <li><strong>For "Apply CSS”:</strong>

  <ul>
   <li>toggles the <code>pageAction</code> icon and title to the “remove” versions.</li>
   <li>applies the CSS using {{WebExtAPIRef("tabs.insertCSS")}}.</li>
  </ul>
 </li>
 <li><strong>For “Remove CSS”:</strong>
  <ul>
   <li>toggles the <code>pageAction</code> icon and title to the “apply” versions.</li>
   <li>removes the CSS using {{WebExtAPIRef("tabs.removeCSS")}}.</li>
  </ul>
 </li>
</ul>

<pre class="brush: js">function toggleCSS(tab) {


 function gotTitle(title) {

    if (title === TITLE_APPLY) {
     browser.pageAction.setIcon({tabId: tab.id, path: "icons/on.svg"});
     browser.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE});
     browser.tabs.insertCSS({code: CSS});
    } else {
     browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"});
     browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY});
     browser.tabs.removeCSS({code: CSS});
    }
 }

 var gettingTitle = browser.pageAction.getTitle({tabId: tab.id});

 gettingTitle.then(gotTitle);
}
</pre>

<p>Finally, to ensure that the <code>pageAction</code> is valid after each update to the tab, a listener on {{WebExtAPIRef("tabs.onUpdated")}} calls <code>initializePageAction()</code> each time the tab is updated to check that the tab is still using a protocol to which the CSS can be applied.</p>

<pre class="brush: js">browser.tabs.onUpdated.addListener((id, changeInfo, tab) =&gt; {
 initializePageAction(tab);
});
</pre>

<h2 id="Some_other_interesting_abilities">Some other interesting abilities</h2>

<p>There are a couple of other Tabs API features that don’t fit into one of the earlier sections:</p>

<ul>
 <li>Capture the visible tab content with {{WebExtAPIRef("tabs.captureVisibleTab")}}.</li>
 <li>Detect the primary language of the content in a tab using {{WebExtAPIRef("tabs.detectLanguage")}}. This could be used, for example, to match the language in your extension’s UI with that of the page it’s running in.</li>
</ul>

<h2 id="Learn_more">Learn more</h2>

<p>If you want to learn more about the Tabs API, check out:</p>

<ul>
 <li><a href="/en-US/Add-ons/WebExtensions/API/tabs">Tabs API reference</a></li>
 <li><a href="/en-US/Add-ons/WebExtensions/Examples">Example extensions</a> (many of which use the Tabs API)</li>
</ul>