Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

この記事はまだボランティアによって 日本語 に翻訳されていません。ぜひ MDN に参加して翻訳を手伝ってください!

Stable

Open, manipulate, and access tabs, and receive tab events.

Usage

Open a tab

You can open a new tab, specifying various properties including location:

var tabs = require("sdk/tabs");
tabs.open("https://www.example.com");

Track tabs

You can register event listeners to be notified when tabs open, close, finish loading DOM content, or are made active or inactive:

var tabs = require("sdk/tabs");

// Listen for tab openings.
tabs.on('open', function onOpen(tab) {
  myOpenTabs.push(tab);
});

// Listen for tab content loads.
tabs.on('ready', function(tab) {
  console.log('tab is loaded', tab.title, tab.url);
});

Access tabs

The module itself can be used as a list of all opened tabs across all windows. In particular, you can enumerate it:

var tabs = require('sdk/tabs');
for (let tab of tabs)
  console.log(tab.title);

You can also access individual tabs by index:

var tabs = require('sdk/tabs');

tabs.on('ready', function () {
  console.log('first: ' + tabs[0].title);
  console.log('last: ' + tabs[tabs.length-1].title);
});

You can access the currently active tab:

var tabs = require('sdk/tabs');

tabs.on('activate', function () {
  console.log('active: ' + tabs.activeTab.url);
});

Track a single tab

Given a tab, you can register event listeners to be notified when the tab is closed, activated or deactivated, or when the page hosted by the tab is loaded or retrieved from the "back-forward cache":

var tabs = require("sdk/tabs");

function onOpen(tab) {
  console.log(tab.url + " is open");
  tab.on("pageshow", logShow);
  tab.on("activate", logActivate);
  tab.on("deactivate", logDeactivate);
  tab.on("close", logClose);
}

function logShow(tab) {
  console.log(tab.url + " is loaded");
}

function logActivate(tab) {
  console.log(tab.url + " is activated");
}

function logDeactivate(tab) {
  console.log(tab.url + " is deactivated");
}

function logClose(tab) {
  console.log(tab.url + " is closed");
}

tabs.on('open', onOpen);

Manipulate a tab

You can get and set various properties of tabs (but note that properties relating to the tab's content, such as the URL, will not contain valid values until after the tab's ready event fires). By setting the url property you can load a new page in the tab:

var tabs = require("sdk/tabs");
tabs.on('activate', function(tab) {
  tab.url = "https://www.example.com";
});

Run scripts in a tab

You can attach a content script to the page hosted in a tab, and use that to access and manipulate the page's content (see the Modifying the Page Hosted by a Tab tutorial):

var tabs = require("sdk/tabs");

tabs.on('activate', function(tab) {
  var worker = tab.attach({
    contentScript: 'self.port.emit("html", document.body.innerHTML);'
  });
  worker.port.on("html", function(message) {
    console.log(message)
  })
});

Note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page.

Attaching stylesheets

New in Firefox 34.

You can't attach style sheets to a tab using tab.attach(), but from Firefox 34 onwards you can attach and detach them using the low-level stylesheet/style and content/mod APIs. Here's an add-on that uses a toggle button to attach a stylesheet to the active tab, and detach it again. The stylesheet is called "style.css" and is located in the add-on's "data" directory:

var tabs = require("sdk/tabs");
var { attach, detach } = require('sdk/content/mod');
var { Style } = require('sdk/stylesheet/style');
var { ToggleButton } = require("sdk/ui/button/toggle");

var style = Style({
  uri: './style.css'
});

var button = ToggleButton({
  id: "stylist",
  label: "stylist",
  icon: "./icon-16.png",
  onChange: function(state) {
    if (state.checked) {
      attach(style, tabs.activeTab);
    }
    else {
      detach(style, tabs.activeTab);
    }
  }
});

Private windows

If your add-on has not opted into private browsing, then you won't see any tabs that are hosted by private browser windows.

Tabs hosted by private browser windows won't be seen if you enumerate the tabs module itself, and you won't receive any events for them.

To learn more about private windows, how to opt into private browsing, and how to support private browsing, refer to the documentation for the private-browsing module.

Converting to XUL tabs

To convert from the high-level Tab objects used in this API to the low-level XUL tab objects used in the tabs/utils API and by traditional add-ons, use the viewFor() function exported by the viewFor module.

To convert back the other way, from a XUL tab to a high-level Tab object, use the modelFor() function, exported by the modelFor module.

Here's an example converting from a high-level Tab to a XUL tab and then back the other way:

var { modelFor } = require("sdk/model/core");
var { viewFor } = require("sdk/view/core");

var tabs = require("sdk/tabs");
var tab_utils = require("sdk/tabs/utils");

function mapHighLevelToLowLevel(tab) {
  // get the XUL tab that corresponds to this high-level tab
  var lowLevelTab = viewFor(tab);
  // now we can, for example, access the tab's content directly
  var browser = tab_utils.getBrowserForTab(lowLevelTab);
  console.log(browser.contentDocument.body.innerHTML);
  // get the high-level tab back from the XUL tab
  var highLevelTab = modelFor(lowLevelTab);
  console.log(highLevelTab.url);
}

tabs.on("ready", mapHighLevelToLowLevel);

Note that directly accessing XUL objects and web content like this means you're no longer protected by the compatibility guarantees made by the SDK's high-level APIs. In particular, your code might not work with multiprocess Firefox.

Globals

Functions

open(options)

Opens a new tab. The new tab will open in the active window or in a new window, depending on the inNewWindow option.

Example

var tabs = require("sdk/tabs");

// Open a new tab on active window and make tab active.
tabs.open("https://www.mysite.com");

// Open a new tab in a new window and make it active.
tabs.open({
  url: "https://www.mysite.com",
  inNewWindow: true
});

// Open a new tab on active window in the background.
tabs.open({
  url: "https://www.mysite.com",
  inBackground: true
});

// Open a new tab as an app tab and do something once it's open.
tabs.open({
  url: "https://www.mysite.com",
  isPinned: true,
  onOpen: function onOpen(tab) {
    // do stuff like listen for content
    // loading.
  }
});
Parameters

options : object
Required options:

Name Type  
url string

String URL to be opened in the new tab. This is a required property.

Optional options:

Name Type  
isPrivate boolean

Boolean which will determine whether the new tab should be private or not. If your add-on does not support private browsing this will have no effect. See the private-browsing documentation for more information. Defaults to false.

inNewWindow boolean

If present and true, a new browser window will be opened and the URL will be opened in the first tab in that window. This is an optional property.

inBackground boolean

If present and true, the new tab will be opened to the right of the active tab and will not be active. This is an optional property.

isPinned boolean

If present and true, then the new tab will be pinned as an app tab.

onOpen function

A callback function that will be registered for the 'open' event. This is an optional property.

onClose function

A callback function that will be registered for the 'close' event. This is an optional property.

onReady function

A callback function that will be registered for the 'ready' event. This is an optional property.

onLoad function

A callback function that will be registered for the 'load' event. This is an optional property.

onPageShow function

A callback function that will be registered for the 'pageshow' event. This is an optional property.

onActivate function

A callback function that will be registered for the 'activate' event. This is an optional property.

onDeactivate function

A callback function that will be registered for the 'deactivate' event. This is an optional property.

Properties

activeTab

The currently active tab in the active window. This property is read-only. To activate a Tab object, call its activate method.

Example

// Get the active tab's title.
var tabs = require("sdk/tabs");
console.log("title of active tab is " + tabs.activeTab.title);

length

The number of open tabs across all windows.

Events

open

This event is emitted when a new tab is opened. This does not mean that the content has loaded, only that the browser tab itself is fully visible to the user.

Properties relating to the tab's content (for example: title, favicon, and url) will not be correct at this point. If you need to access these properties, listen for the ready event:

var tabs = require("sdk/tabs");
tabs.on('open', function(tab){
  tab.on('ready', function(tab){
    console.log(tab.url);
  });
});
Arguments

Tab : Listeners are passed the tab object that just opened.

close

This event is emitted when a tab is closed. When a window is closed this event will be emitted for each of the open tabs in that window.

Arguments

Tab : Listeners are passed the tab object that has closed.

ready

This event is emitted when the DOM for a tab's content is ready. It is equivalent to the DOMContentLoaded event for the given content page.

A single tab will emit this event every time the DOM is loaded: so it will be emitted again if the tab's location changes or the content is reloaded.

After this event has been emitted, all properties relating to the tab's content can be used.

Arguments

Tab : Listeners are passed the tab object that has loaded.

activate

This event is emitted when an inactive tab is made active.

Arguments

Tab : Listeners are passed the tab object that has become active.

deactivate

This event is emitted when the active tab is made inactive.

Arguments

Tab : Listeners are passed the tab object that has become inactive.

Tab

A Tab instance represents a single open tab. It contains various tab properties, several methods for manipulation, as well as per-tab event registration.

Tabs emit all the events described in the Events section. Listeners are passed the Tab object that triggered the event.

Methods

pin()

Pins this tab as an app tab.

unpin()

Unpins this tab.

close(callback)

Closes this tab.

Parameters

callback : function
A function to be called when the tab finishes its closing process. This is an optional argument.

reload()

Reloads this tab.

activate()

Makes this tab active, which will bring this tab to the foreground.

getThumbnail()

Returns thumbnail data URI of the page currently loaded in this tab.

attach(options)

Attach one or more scripts to the document loaded in the tab. Note that by attaching inside ready event, this becomes tab-centric: if the user navigates to a new page in the same tab, then the content scripts will be reattached to the new page.

Example

var tabs = require("sdk/tabs");

tabs.on('ready', function(tab) {
  var worker = tab.attach({
      contentScript:
        'document.body.style.border = "5px solid red";'
  });
});
Parameters

options : object
Optional options:

Name Type  
contentScriptFile string,array

The local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. Optional.

contentScript string,array

A string or an array of strings of code to be evaluated in the context. Content scripts specified by this option are loaded after those specified by the contentScriptFile option. Optional.

contentScriptOptions object

You can use this option to define read-only values for your content scripts.

The option consists of an object literal listing name:value pairs for the values you want to provide to the content script. For example:

// main.js

const tabs = require("sdk/tabs");

tabs.open({
  url: "./page.html",
  onReady: function(tab) {
    tab.attach({
      contentScriptFile: "./content-script.js",
      contentScriptOptions: {
        a: "blah"
      }
    });
  }
});

The values are accessible to content scripts via the self.options property:

// content-script.js

alert(self.options.a);
onMessage function

A function called when the content worker receives a message from content scripts. Listeners are passed a single argument, the message posted from the content script. Optional.

onError function A function called when the content worker receives an error from content scripts. Listeners are passed a single argument, error, which is the error posted from the content script and an object of type Error. Optional
Returns

Worker : The Worker object can be used to communicate with the content script. See Content Scripts guide to learn the details.

Properties

id

The unique id for the tab. This property is read-only.

title

The title of the tab (usually the title of the page currently loaded in the tab) This property can be set to change the tab title.

url

The URL of the page currently loaded in the tab. This property can be set to load a different URL in the tab.

favicon

The URL of the favicon for the page currently loaded in the tab. This property is read-only.

This property is deprecated. From version 1.15, use the favicon module's getFavicon() function instead.

contentType

This is currently an experimental API, so we might change it in future releases.

Returns the MIME type that the document currently loaded in the tab is being rendered as. This may come from HTTP headers or other sources of MIME information, and might be affected by automatic type conversions performed by either the browser or extensions. This property is read-only.

index

The index of the tab relative to other tabs in the application window. This property can be set to change its relative position.

isPinned

Whether or not this tab is pinned as an app tab. This property is read-only.

window

The window object for this tab.

readyState

New in Firefox 33.

A string telling you the load state of the document hosted by this tab. This corresponds directly to Document.readyState. It has one of four possible values:

  • "uninitialized": the tab's document is not yet loading
  • "loading": the tab's document is still in the process of loading
  • "interactive": the tab's document has loaded and is parsed, but resources such as images and stylesheets may still be loading
  • "complete": the tab's document and all resources are fully loaded

Once a tab's readyState has entered "interactive", you can retrieve properties such as the document's URL.

Events

close

This event is emitted when the tab is closed. It's also emitted when the tab's window is closed.

Arguments

Tab : Listeners are passed the tab object.

ready

This event is emitted when the DOM for the tab's content is ready. It is equivalent to the DOMContentLoaded event for the given content page. At this point the document itself is fully loaded and parsed, but resources such as stylesheets and images may still be loading.

A single tab will emit this event every time the DOM is loaded: so it will be emitted again if the tab's location changes or the content is reloaded. After this event has been emitted, all properties relating to the tab's content can be used.

Arguments

Tab : Listeners are passed the tab object.

load

This event is emitted when the page for the tab's content is loaded. It is equivalent to the load event for the given content page. At this point the document and its resources, such as images and stylesheets, have finished loading.

This event can be used for pages that do not have a DOMContentLoaded event, like images. For pages that have a DOMContentLoaded event, load is fired after ready.

A single tab will emit this event every time the page is loaded: so it will be emitted again if the tab's location changes or the content is reloaded. After this event has been emitted, all properties relating to the tab's content can be used.

Arguments

Tab : Listeners are passed the tab object.

pageshow

The pageshow event is emitted when the page for a tab's content is loaded. It is equivalent to the pageshow event for the given content page.

This event is similar to the load and ready events, except unlike load and ready, pageshow is triggered if the page was retrieved from the bfcache. This means that if the user loads a page, loads a new page, then moves back to the previous page using the "Back" button, the pageshow event is emitted when the user moves back to the previous page, while the load and ready events are not.

This event is not emitted when the tab is made the active tab: to get notified about that, you need to listen to the activate event.

After this event has been emitted, all properties relating to the tab's content can be used. It is emitted after load and ready.

Arguments

Tab : Listeners are passed the tab object.

persisted : Listeners are passed a boolean value indicating whether or not the page was loaded from the bfcache.

activate

This event is emitted when the tab is made active.

Note that you cannot guarantee that a tab's content, or even its url, are initialized at the time activate is emitted. This is because when a new tab is opened, its activate event may be emitted before the content is loaded.

You can use the tab's readyState property to determine whether the tab's content and url will be available: if readyState is uninitialized or loading, then you can't access the tab's properties and must wait for the tab's ready event.

Arguments

Tab : Listeners are passed the tab object.

deactivate

This event is emitted when the tab is made inactive.

Arguments

Tab : Listeners are passed the tab object.

ドキュメントのタグと貢献者

タグ: 
 このページの貢献者: wbamberg, maybe, Mahdi, evold, XrXrXr, Miryafa, tagawa, Delapouite
 最終更新者: wbamberg,