From 4acbedb1fe0f43802c64027cf7cbf81441297a95 Mon Sep 17 00:00:00 2001 From: "mpcomplete@chromium.org" Date: Fri, 6 Nov 2009 19:48:41 +0000 Subject: Revamp the docs for message passing, including the new sendRequest API. BUG=26830 Review URL: http://codereview.chromium.org/375006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@31265 0039d316-1c4b-4281-b951-d872f2087c98 --- chrome/common/extensions/api/extension_api.json | 18 +- chrome/common/extensions/docs/api_index.html | 1 + chrome/common/extensions/docs/api_other.html | 1 + chrome/common/extensions/docs/autoupdate.html | 1 + .../common/extensions/docs/background_pages.html | 1 + chrome/common/extensions/docs/bookmarks.html | 1 + chrome/common/extensions/docs/browserAction.html | 1 + chrome/common/extensions/docs/content_scripts.html | 74 +-- chrome/common/extensions/docs/devguide.html | 1 + chrome/common/extensions/docs/devtools.html | 1 + chrome/common/extensions/docs/events.html | 1 + chrome/common/extensions/docs/extension.html | 45 +- chrome/common/extensions/docs/getstarted.html | 1 + chrome/common/extensions/docs/hosting.html | 1 + chrome/common/extensions/docs/i18n.html | 1 + chrome/common/extensions/docs/index.html | 1 + chrome/common/extensions/docs/manifest.html | 1 + chrome/common/extensions/docs/match_patterns.html | 1 + chrome/common/extensions/docs/messaging.html | 622 +++++++++++++++++++++ chrome/common/extensions/docs/npapi.html | 1 + chrome/common/extensions/docs/options.html | 1 + chrome/common/extensions/docs/override.html | 1 + chrome/common/extensions/docs/overview.html | 1 + chrome/common/extensions/docs/packaging.html | 1 + chrome/common/extensions/docs/pageAction.html | 1 + .../extensions/docs/static/content_scripts.html | 64 +-- .../common/extensions/docs/static/messaging.html | 217 +++++++ chrome/common/extensions/docs/tabs.html | 45 +- .../extensions/docs/template/api_template.html | 1 + chrome/common/extensions/docs/test.html | 1 + chrome/common/extensions/docs/themes.html | 1 + chrome/common/extensions/docs/toolstrip.html | 1 + chrome/common/extensions/docs/tut_debugging.html | 1 + chrome/common/extensions/docs/tutorials.html | 1 + chrome/common/extensions/docs/windows.html | 1 + chrome/common/extensions/docs/xhr.html | 1 + 36 files changed, 973 insertions(+), 141 deletions(-) create mode 100644 chrome/common/extensions/docs/messaging.html create mode 100644 chrome/common/extensions/docs/static/messaging.html (limited to 'chrome') diff --git a/chrome/common/extensions/api/extension_api.json b/chrome/common/extensions/api/extension_api.json index b6f00e3..baf1660 100755 --- a/chrome/common/extensions/api/extension_api.json +++ b/chrome/common/extensions/api/extension_api.json @@ -69,7 +69,14 @@ { "type": "function", "name": "responseCallback", - "optional": true + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The JSON response object sent by the handler of the request." + } + ] } ] }, @@ -461,7 +468,14 @@ { "type": "function", "name": "responseCallback", - "optional": true + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The JSON response object sent by the handler of the request." + } + ] } ] }, diff --git a/chrome/common/extensions/docs/api_index.html b/chrome/common/extensions/docs/api_index.html index 19a4131..4021cff 100644 --- a/chrome/common/extensions/docs/api_index.html +++ b/chrome/common/extensions/docs/api_index.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/api_other.html b/chrome/common/extensions/docs/api_other.html index 935500d..44109037 100644 --- a/chrome/common/extensions/docs/api_other.html +++ b/chrome/common/extensions/docs/api_other.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/autoupdate.html b/chrome/common/extensions/docs/autoupdate.html index 9b083d3..3250c73 100644 --- a/chrome/common/extensions/docs/autoupdate.html +++ b/chrome/common/extensions/docs/autoupdate.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/background_pages.html b/chrome/common/extensions/docs/background_pages.html index 2acdad4..13e9639 100644 --- a/chrome/common/extensions/docs/background_pages.html +++ b/chrome/common/extensions/docs/background_pages.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/bookmarks.html b/chrome/common/extensions/docs/bookmarks.html index 36afd0b..4903bd7 100644 --- a/chrome/common/extensions/docs/bookmarks.html +++ b/chrome/common/extensions/docs/bookmarks.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/browserAction.html b/chrome/common/extensions/docs/browserAction.html index be78639..a01ca9c 100644 --- a/chrome/common/extensions/docs/browserAction.html +++ b/chrome/common/extensions/docs/browserAction.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/content_scripts.html b/chrome/common/extensions/docs/content_scripts.html index 9c8bf16..93cb4d1 100644 --- a/chrome/common/extensions/docs/content_scripts.html +++ b/chrome/common/extensions/docs/content_scripts.html @@ -121,6 +121,7 @@ @@ -175,20 +176,13 @@
  • - Messaging -
      -
    1. - h3Name -
    2. -
    -
  • Communication with the embedding page
    1. h3Name
    -
  • +
  • Referring to extension files
    1. @@ -289,7 +283,7 @@ These limitations aren't as bad as they sound. Content scripts can indirectly use the chrome.* APIs, get access to extension data, and request extension actions -by exchanging messages +by exchanging messages with their parent extension. Content scripts can also communicate with web pages @@ -404,68 +398,8 @@ document.getElementById("button").onclick = function() {

      Another important benefit of isolated worlds is that they completely separate the JavaScript on the page from the JavaScript in extensions. This allows us to offer extra functionality to content scripts that should not be accessible from web pages without worrying about web pages accessing it. -

      Messaging

      - -

      Content scripts can communicate with their parent extension using message passing. A message channel can be opened by either the content script or an extension page. Each side of the channel has a Port object which can be used to send messages to the other side. The messages can contain any valid JSON object (null, boolean, number, string, array, or object). - -

      The content script opens a channel to the extension using the chrome.extension.connect() method. The parent extension can also open a channel to a content script in a given tab by calling chrome.tabs.connect(tabId). In either case, the onConnect event is fired in the targeted page(s), and a connection is established. - -

      When a channel is opened from a content script to an extension, the event is -fired in all views in the extension. Any view can receive the event. - -

      For example, suppose you want to write a simple login manager. You want a toolstrip button that lights up when a content script detects a "login" element in a page, and fills in the login info when you press the button. - -

      Your content script would look like this: - -

      contentscript.js
      -================
      -var e = document.getElementById("login");
      -
      -// Create a short-lived named channel to the extension and send a single
      -// message through it.
      -var port = chrome.extension.connect({name: "notifyChannel"});
      -port.postMessage({found: (e != undefined)});
      -
      -// Also listen for new channels from the extension for when the button is
      -// pressed.
      -chrome.extension.onConnect.addListener(function(port) {
      -  console.assert(port.name == "buttonClickedChannel");
      -  port.onMessage.addListener(function(msg) {
      -    if (msg.buttonClicked) {
      -      e.value = msg.passwordValue;
      -    }
      -  });
      -});
      -
      - -

      with a toolstrip that looks like: - -

      toolstrip.html
      -==============
      -<div class="toolstrip-button" id="btn" onclick="onClick()">
      -  Fill Password
      -</div>
      -<script>
      -// Listen for notifications from the content script.
      -chrome.extension.onConnect.addListener(function(port) {
      -  console.assert(port.name == "notifyChannel");
      -  port.onMessage.addListener(function(msg) {
      -    // Color our button based on whether a login element was found.
      -    var color = msg.found ? "blue" : "grey";
      -    document.getElementById("btn").style.backgroundColor = color;
      -  });
      -});
      -function onClick() {
      -  // Send our password to the current tab when clicked.
      -  chrome.tabs.getSelected(null, function(tab) {
      -    var port = chrome.tabs.connect(tab.id, {name: "buttonClickedChannel"});
      -    port.postMessage({buttonClicked: true});
      -  });
      -}
      -</script>
      -
      -

      Communication with the embedding page

      +

      Communication with the embedding page

      Although the execution environments of content scripts and the pages that host them are isolated from each other, they share access to the page's DOM. If the page wishes to communicate with the content script (or with the extension via the content script), it must do so through the shared DOM.

      diff --git a/chrome/common/extensions/docs/devguide.html b/chrome/common/extensions/docs/devguide.html index 3a58f42..4a4a488 100644 --- a/chrome/common/extensions/docs/devguide.html +++ b/chrome/common/extensions/docs/devguide.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/devtools.html b/chrome/common/extensions/docs/devtools.html index 98fd74b..b39c0eb 100644 --- a/chrome/common/extensions/docs/devtools.html +++ b/chrome/common/extensions/docs/devtools.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/events.html b/chrome/common/extensions/docs/events.html index 8983491..b0620b2 100644 --- a/chrome/common/extensions/docs/events.html +++ b/chrome/common/extensions/docs/events.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/extension.html b/chrome/common/extensions/docs/extension.html index 2174eae..bd0c963 100644 --- a/chrome/common/extensions/docs/extension.html +++ b/chrome/common/extensions/docs/extension.html @@ -121,6 +121,7 @@ @@ -1357,11 +1358,49 @@ For details, see

      -
      function(null) {...});
      +
      function(any response) {...});
      -
      +
      -
      +
      + response + + + +
      + ( + + + + Type + + + + array of + + any + + + ) +
      + +
      +
      + +
      The JSON response object sent by the handler of the request.
      + + +
      +
      +
      +
      +
      +
      +
      +
      +
      diff --git a/chrome/common/extensions/docs/getstarted.html b/chrome/common/extensions/docs/getstarted.html index 05b22d4..0ed3bfc 100644 --- a/chrome/common/extensions/docs/getstarted.html +++ b/chrome/common/extensions/docs/getstarted.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/hosting.html b/chrome/common/extensions/docs/hosting.html index 3068556..68521e2 100644 --- a/chrome/common/extensions/docs/hosting.html +++ b/chrome/common/extensions/docs/hosting.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/i18n.html b/chrome/common/extensions/docs/i18n.html index fb458bb..ec45a96 100644 --- a/chrome/common/extensions/docs/i18n.html +++ b/chrome/common/extensions/docs/i18n.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/index.html b/chrome/common/extensions/docs/index.html index f82273d..76fcc2d 100644 --- a/chrome/common/extensions/docs/index.html +++ b/chrome/common/extensions/docs/index.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/manifest.html b/chrome/common/extensions/docs/manifest.html index 145be1f..41170b0 100644 --- a/chrome/common/extensions/docs/manifest.html +++ b/chrome/common/extensions/docs/manifest.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/match_patterns.html b/chrome/common/extensions/docs/match_patterns.html index 307506a..4ee01d4 100644 --- a/chrome/common/extensions/docs/match_patterns.html +++ b/chrome/common/extensions/docs/match_patterns.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/messaging.html b/chrome/common/extensions/docs/messaging.html new file mode 100644 index 0000000..1d17866 --- /dev/null +++ b/chrome/common/extensions/docs/messaging.html @@ -0,0 +1,622 @@ + + + + + + + + Message Passing
      + + +
      + + +
      +
      + paramName + + + +
      + ( + optional + + + Type + + + + array of + + paramType + + + ) +
      + +
      +
      +
      + Undocumented. +
      +
      + Description of this parameter from the json schema. +
      + + +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      + + + + + +
      + +
      + +
      + +
      + +
      +

      Contents

      +
        +
      1. + Simple one-time requests +
          +
        1. + h3Name +
        2. +
        +
      2. + Long-lived connections +
          +
        1. + h3Name +
        2. +
        +
      3. + Cross-extension messaging +
          +
        1. + h3Name +
        2. +
        +
      4. +
        +
      5. + API reference +
          +
        1. + Properties +
            +
          1. + propertyName +
          2. +
          +
        2. +
        3. + Methods +
            +
          1. + methodName +
          2. +
          +
        4. +
        5. + Events +
            +
          1. + eventName +
          2. +
          +
        6. +
        7. + Types +
            +
          1. + id +
          2. +
          +
        8. +
        +
      6. +
        +
      +
      + + + +
      Message Passing
      +
      true
      + +

      +Since content scripts run in the context of a web page and not the extension, +they often need some way of communicating with the rest of the extension. For +example, an RSS reader extension might use content scripts to detect the +presence of an RSS feed on a page, then notify the background page in order to +display a page action icon for that page. + +

      +Communication between extensions and their content scripts works by using +message passing. Either side can listen for messages sent from the other end, +and respond on the same channel. A message can contain any valid JSON object +(null, boolean, number, string, array, or object). There is a simple API for +one-time requests +and a more complex API that allows you to have +long-lived connections +for exchanging multiple messages with a shared context. It is also possible to +send a message to another extension if you know its ID, which is covered in +the +cross-extension messages +section. + + +

      Simple one-time requests

      +

      +If you only need to send a single message to another part of your extension +(and optionally get a response back), you should use the simplified +chrome.extension.sendRequest() +or +chrome.tabs.sendRequest() +methods. This lets you send a one-time JSON-serializable message from a +content script to extension, or vice versa, respectively. An optional +callback parameter allows you handle the response from the other side, if +there is one. + +

      +Sending a request from a content script looks like this: +

      contentscript.js
      +================
      +chrome.extension.sendRequest({greeting: "hello"}, function(response) {
      +  console.log(response.farewell);
      +});
      +
      + +

      +Sending a request from the extension to a content script looks very similar, +except that you need to specify which tab to send it to. This example +demonstrates sending a message to the content script in the selected tab. +

      background.html
      +===============
      +chrome.tabs.getSelected(null, function(tab) {
      +  chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
      +    console.log(response.farewell);
      +  });
      +});
      +
      + +

      +On the receiving end, you need to set up an +chrome.extension.onRequest +event listener to handle the message. This looks the same from a content +script or extension page. The request will remain open until you call +sendResponse, so it is good practice to call sendResponse with an empty +object to allow the request to be cleaned up. +

      chrome.extension.onRequest.addListener(
      +  function(request, sender, sendResponse) {
      +    console.log(sender.tab ?
      +                "from a content script:" + sender.tab.url :
      +                "from the extension");
      +    if (request.greeting == "hello")
      +      sendResponse({farewell: "goodbye"});
      +    else
      +      sendResponse({}); // snub them.
      +  });
      +
      + + +

      Long-lived connections

      +

      +Sometimes it's useful to have a conversation that lasts longer than a single +request and response. In this case, you can open a long-lived channel from +your content script to an extension page, or vice versa, using +chrome.extension.connect() +or +chrome.tabs.connect() respectively. The +channel can optionally have a name, allowing you to distinguish between +different types of connections. + +

      +One use case might be an automatic form fill extension. The content script +could open a channel to the extension page for a particular login, and send a +message to the extension for each input element on the page to request the +form data to fill in. The shared connection allows the extension to keep +shared state linking the several messages coming from the content script. + +

      +When establishing a connection, each end is given a +Port +object which is used for sending and receiving messages through that +connection. + +

      +Here is how you open a channel from a content script, and send and listen for +messages: +

      contentscript.js
      +================
      +var port = chrome.extension.connect({name: "knockknock"});
      +port.postMessage({joke: "Knock knock"});
      +port.onMessage.addListener(function(msg) {
      +  if (msg.question == "Who's there?")
      +    port.postMessage({answer: "Madame"});
      +  else if (msg.question == "Madame who?")
      +    port.postMessage({answer: "Madame... Bovary");
      +});
      +
      + +

      +Sending a request from the extension to a content script looks very similar, +except that you need to specify which tab to connect to. Simply replace the +call to connect in the above example with +chrome.tabs.connect(tabId, {name: +"knockknock"}). + +

      +In order to handle incoming connections, you need to set up a +chrome.extension.onConnect +event listener. This looks the same from a content script or an extension +page. When another part of your extension calls "connect()", this event is +fired, along with the +Port +object you can use to send and receive messages through the connection. Here's +what it looks like to respond to incoming connections: +

      chrome.extension.onConnect.addListener(function(port) {
      +  console.assert(port.name == "knockknock");
      +  port.onMessage.addListener(function(msg) {
      +    if (msg.joke == "Knock knock")
      +      port.postMessage({question: "Who's there?"});
      +    else if (msg.answer == "Madame")
      +      port.postMessage({question: "Madame who?"});
      +    else if (msg.answer == "Madame... Bovary")
      +      port.postMessage({question: "I don't get it."});
      +  });
      +});
      +
      + +

      +You may want to find out when a connection is closed, for example if you are +maintaining separate state for each open port. For this you can listen to the +Port.onDisconnect +event. This event is fired either when the other side of the channel manually +calls +Port.disconnect(), or when the page +containing the port is unloaded (for example if the tab is navigated). +onDisconnect is guaranteed to be fired only once for any given port. + + +

      Cross-extension messaging

      +

      +In addition to sending messages between different components in your +extension, you can use the messaging API to communicate with other extensions. +This lets you expose a public API that other extensions can take advantage of. + +

      +Listening for incoming requests and connections is similar to the internal +case, except you use the +chrome.extension.onRequestExternal +or +chrome.extension.onConnectExternal +methods. Here's an example of each: +

      // For simple requests:
      +chrome.extension.onRequestExternal.addListener(
      +  function(request, sender, sendResponse) {
      +    if (sender.id == blacklistedExtension)
      +      sendResponse({});  // don't allow this extension access
      +    else if (request.getTargetData)
      +      sendResponse({targetData: targetData});
      +    else if (request.activateLasers) {
      +      var success = activateLasers();
      +      sendResponse({activateLasers: success});
      +    }
      +  });
      +
      +// For long-lived connections:
      +chrome.extension.onConnectExternal.addListener(function(port) {
      +  port.onMessage.addListener(function(msg) {
      +    // See other examples for sample onMessage handlers.
      +  });
      +});
      +
      + +

      +Likewise, sending a message to another extension is similar to sending one +within your extension. The only difference is that you must pass the ID of the +extension you want to communicate with. For example: +

      // The ID of the extension we want to talk to.
      +var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
      +
      +// Make a simple request:
      +chrome.extension.sendRequest(laserExtensionId, {getTargetData: true},
      +  function(response) {
      +    if (targetInRange(response.targetData))
      +      chrome.extension.sendRequest(laserExtensionId, {activateLasers: true});
      +  });
      +
      +// Start a long-running conversation:
      +var port = chrome.extension.connectExternal(laserExtensionId);
      +port.postMessage(...);
      +
      +
      + + + +
      +
      + +
      + + diff --git a/chrome/common/extensions/docs/npapi.html b/chrome/common/extensions/docs/npapi.html index e17e794..9299f62 100644 --- a/chrome/common/extensions/docs/npapi.html +++ b/chrome/common/extensions/docs/npapi.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/options.html b/chrome/common/extensions/docs/options.html index 6d9212d..5ef07ff 100644 --- a/chrome/common/extensions/docs/options.html +++ b/chrome/common/extensions/docs/options.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/override.html b/chrome/common/extensions/docs/override.html index 145a5a7..5a6b4de 100644 --- a/chrome/common/extensions/docs/override.html +++ b/chrome/common/extensions/docs/override.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/overview.html b/chrome/common/extensions/docs/overview.html index 7ab3dc4..aa7f735 100644 --- a/chrome/common/extensions/docs/overview.html +++ b/chrome/common/extensions/docs/overview.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/packaging.html b/chrome/common/extensions/docs/packaging.html index d2369f5..61b67ef 100644 --- a/chrome/common/extensions/docs/packaging.html +++ b/chrome/common/extensions/docs/packaging.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/pageAction.html b/chrome/common/extensions/docs/pageAction.html index f9c6575..b69cef6 100644 --- a/chrome/common/extensions/docs/pageAction.html +++ b/chrome/common/extensions/docs/pageAction.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/static/content_scripts.html b/chrome/common/extensions/docs/static/content_scripts.html index 9f1edf1..83a7e8e 100644 --- a/chrome/common/extensions/docs/static/content_scripts.html +++ b/chrome/common/extensions/docs/static/content_scripts.html @@ -47,7 +47,7 @@ These limitations aren't as bad as they sound. Content scripts can indirectly use the chrome.* APIs, get access to extension data, and request extension actions -by exchanging messages +by exchanging messages with their parent extension. Content scripts can also communicate with web pages @@ -162,68 +162,6 @@ document.getElementById("button").onclick = function() {

      Another important benefit of isolated worlds is that they completely separate the JavaScript on the page from the JavaScript in extensions. This allows us to offer extra functionality to content scripts that should not be accessible from web pages without worrying about web pages accessing it. -

      Messaging

      - -

      Content scripts can communicate with their parent extension using message passing. A message channel can be opened by either the content script or an extension page. Each side of the channel has a Port object which can be used to send messages to the other side. The messages can contain any valid JSON object (null, boolean, number, string, array, or object). - -

      The content script opens a channel to the extension using the chrome.extension.connect() method. The parent extension can also open a channel to a content script in a given tab by calling chrome.tabs.connect(tabId). In either case, the onConnect event is fired in the targeted page(s), and a connection is established. - -

      When a channel is opened from a content script to an extension, the event is -fired in all views in the extension. Any view can receive the event. - -

      For example, suppose you want to write a simple login manager. You want a toolstrip button that lights up when a content script detects a "login" element in a page, and fills in the login info when you press the button. - -

      Your content script would look like this: - -

      -contentscript.js
      -================
      -var e = document.getElementById("login");
      -
      -// Create a short-lived named channel to the extension and send a single
      -// message through it.
      -var port = chrome.extension.connect({name: "notifyChannel"});
      -port.postMessage({found: (e != undefined)});
      -
      -// Also listen for new channels from the extension for when the button is
      -// pressed.
      -chrome.extension.onConnect.addListener(function(port) {
      -  console.assert(port.name == "buttonClickedChannel");
      -  port.onMessage.addListener(function(msg) {
      -    if (msg.buttonClicked) {
      -      e.value = msg.passwordValue;
      -    }
      -  });
      -});
      -
      - -

      with a toolstrip that looks like: - -

      -toolstrip.html
      -==============
      -<div class="toolstrip-button" id="btn" onclick="onClick()">
      -  Fill Password
      -</div>
      -<script>
      -// Listen for notifications from the content script.
      -chrome.extension.onConnect.addListener(function(port) {
      -  console.assert(port.name == "notifyChannel");
      -  port.onMessage.addListener(function(msg) {
      -    // Color our button based on whether a login element was found.
      -    var color = msg.found ? "blue" : "grey";
      -    document.getElementById("btn").style.backgroundColor = color;
      -  });
      -});
      -function onClick() {
      -  // Send our password to the current tab when clicked.
      -  chrome.tabs.getSelected(null, function(tab) {
      -    var port = chrome.tabs.connect(tab.id, {name: "buttonClickedChannel"});
      -    port.postMessage({buttonClicked: true});
      -  });
      -}
      -</script>
      -

      Communication with the embedding page

      diff --git a/chrome/common/extensions/docs/static/messaging.html b/chrome/common/extensions/docs/static/messaging.html new file mode 100644 index 0000000..b850fad --- /dev/null +++ b/chrome/common/extensions/docs/static/messaging.html @@ -0,0 +1,217 @@ +
      Message Passing
      +
      true
      + +

      +Since content scripts run in the context of a web page and not the extension, +they often need some way of communicating with the rest of the extension. For +example, an RSS reader extension might use content scripts to detect the +presence of an RSS feed on a page, then notify the background page in order to +display a page action icon for that page. + +

      +Communication between extensions and their content scripts works by using +message passing. Either side can listen for messages sent from the other end, +and respond on the same channel. A message can contain any valid JSON object +(null, boolean, number, string, array, or object). There is a simple API for +one-time requests +and a more complex API that allows you to have +long-lived connections +for exchanging multiple messages with a shared context. It is also possible to +send a message to another extension if you know its ID, which is covered in +the +cross-extension messages +section. + + +

      Simple one-time requests

      +

      +If you only need to send a single message to another part of your extension +(and optionally get a response back), you should use the simplified +chrome.extension.sendRequest() +or +chrome.tabs.sendRequest() +methods. This lets you send a one-time JSON-serializable message from a +content script to extension, or vice versa, respectively. An optional +callback parameter allows you handle the response from the other side, if +there is one. + +

      +Sending a request from a content script looks like this: +

      +contentscript.js
      +================
      +chrome.extension.sendRequest({greeting: "hello"}, function(response) {
      +  console.log(response.farewell);
      +});
      +
      + +

      +Sending a request from the extension to a content script looks very similar, +except that you need to specify which tab to send it to. This example +demonstrates sending a message to the content script in the selected tab. +

      +background.html
      +===============
      +chrome.tabs.getSelected(null, function(tab) {
      +  chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
      +    console.log(response.farewell);
      +  });
      +});
      +
      + +

      +On the receiving end, you need to set up an +chrome.extension.onRequest +event listener to handle the message. This looks the same from a content +script or extension page. The request will remain open until you call +sendResponse, so it is good practice to call sendResponse with an empty +object to allow the request to be cleaned up. +

      +chrome.extension.onRequest.addListener(
      +  function(request, sender, sendResponse) {
      +    console.log(sender.tab ?
      +                "from a content script:" + sender.tab.url :
      +                "from the extension");
      +    if (request.greeting == "hello")
      +      sendResponse({farewell: "goodbye"});
      +    else
      +      sendResponse({}); // snub them.
      +  });
      +
      + + +

      Long-lived connections

      +

      +Sometimes it's useful to have a conversation that lasts longer than a single +request and response. In this case, you can open a long-lived channel from +your content script to an extension page, or vice versa, using +chrome.extension.connect() +or +chrome.tabs.connect() respectively. The +channel can optionally have a name, allowing you to distinguish between +different types of connections. + +

      +One use case might be an automatic form fill extension. The content script +could open a channel to the extension page for a particular login, and send a +message to the extension for each input element on the page to request the +form data to fill in. The shared connection allows the extension to keep +shared state linking the several messages coming from the content script. + +

      +When establishing a connection, each end is given a +Port +object which is used for sending and receiving messages through that +connection. + +

      +Here is how you open a channel from a content script, and send and listen for +messages: +

      +contentscript.js
      +================
      +var port = chrome.extension.connect({name: "knockknock"});
      +port.postMessage({joke: "Knock knock"});
      +port.onMessage.addListener(function(msg) {
      +  if (msg.question == "Who's there?")
      +    port.postMessage({answer: "Madame"});
      +  else if (msg.question == "Madame who?")
      +    port.postMessage({answer: "Madame... Bovary");
      +});
      +
      + +

      +Sending a request from the extension to a content script looks very similar, +except that you need to specify which tab to connect to. Simply replace the +call to connect in the above example with +chrome.tabs.connect(tabId, {name: +"knockknock"}). + +

      +In order to handle incoming connections, you need to set up a +chrome.extension.onConnect +event listener. This looks the same from a content script or an extension +page. When another part of your extension calls "connect()", this event is +fired, along with the +Port +object you can use to send and receive messages through the connection. Here's +what it looks like to respond to incoming connections: +

      +chrome.extension.onConnect.addListener(function(port) {
      +  console.assert(port.name == "knockknock");
      +  port.onMessage.addListener(function(msg) {
      +    if (msg.joke == "Knock knock")
      +      port.postMessage({question: "Who's there?"});
      +    else if (msg.answer == "Madame")
      +      port.postMessage({question: "Madame who?"});
      +    else if (msg.answer == "Madame... Bovary")
      +      port.postMessage({question: "I don't get it."});
      +  });
      +});
      +
      + +

      +You may want to find out when a connection is closed, for example if you are +maintaining separate state for each open port. For this you can listen to the +Port.onDisconnect +event. This event is fired either when the other side of the channel manually +calls +Port.disconnect(), or when the page +containing the port is unloaded (for example if the tab is navigated). +onDisconnect is guaranteed to be fired only once for any given port. + + +

      Cross-extension messaging

      +

      +In addition to sending messages between different components in your +extension, you can use the messaging API to communicate with other extensions. +This lets you expose a public API that other extensions can take advantage of. + +

      +Listening for incoming requests and connections is similar to the internal +case, except you use the +chrome.extension.onRequestExternal +or +chrome.extension.onConnectExternal +methods. Here's an example of each: +

      +// For simple requests:
      +chrome.extension.onRequestExternal.addListener(
      +  function(request, sender, sendResponse) {
      +    if (sender.id == blacklistedExtension)
      +      sendResponse({});  // don't allow this extension access
      +    else if (request.getTargetData)
      +      sendResponse({targetData: targetData});
      +    else if (request.activateLasers) {
      +      var success = activateLasers();
      +      sendResponse({activateLasers: success});
      +    }
      +  });
      +
      +// For long-lived connections:
      +chrome.extension.onConnectExternal.addListener(function(port) {
      +  port.onMessage.addListener(function(msg) {
      +    // See other examples for sample onMessage handlers.
      +  });
      +});
      +
      + +

      +Likewise, sending a message to another extension is similar to sending one +within your extension. The only difference is that you must pass the ID of the +extension you want to communicate with. For example: +

      +// The ID of the extension we want to talk to.
      +var laserExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
      +
      +// Make a simple request:
      +chrome.extension.sendRequest(laserExtensionId, {getTargetData: true},
      +  function(response) {
      +    if (targetInRange(response.targetData))
      +      chrome.extension.sendRequest(laserExtensionId, {activateLasers: true});
      +  });
      +
      +// Start a long-running conversation:
      +var port = chrome.extension.connectExternal(laserExtensionId);
      +port.postMessage(...);
      +
      diff --git a/chrome/common/extensions/docs/tabs.html b/chrome/common/extensions/docs/tabs.html index 39ff3fc..16dddc4 100644 --- a/chrome/common/extensions/docs/tabs.html +++ b/chrome/common/extensions/docs/tabs.html @@ -121,6 +121,7 @@ @@ -2926,11 +2927,49 @@ For example:

      -
      function(null) {...});
      +
      function(any response) {...});
      -
      +
      -
      +
      + response + + + +
      + ( + + + + Type + + + + array of + + any + + + ) +
      + +
      +
      + +
      The JSON response object sent by the handler of the request.
      + + +
      +
      +
      +
      +
      +
      +
      +
      +
      diff --git a/chrome/common/extensions/docs/template/api_template.html b/chrome/common/extensions/docs/template/api_template.html index 518ac09..763c685 100644 --- a/chrome/common/extensions/docs/template/api_template.html +++ b/chrome/common/extensions/docs/template/api_template.html @@ -106,6 +106,7 @@
    2. Background Pages
    3. Content Scripts
    4. Cross-Origin XHR
    5. +
    6. Message Passing
    7. NPAPI Plugins
    8. diff --git a/chrome/common/extensions/docs/test.html b/chrome/common/extensions/docs/test.html index 2a703c9..128e4a6 100644 --- a/chrome/common/extensions/docs/test.html +++ b/chrome/common/extensions/docs/test.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/themes.html b/chrome/common/extensions/docs/themes.html index 06b0647..a142b9b 100644 --- a/chrome/common/extensions/docs/themes.html +++ b/chrome/common/extensions/docs/themes.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/toolstrip.html b/chrome/common/extensions/docs/toolstrip.html index 8b7ef70..a337f25 100644 --- a/chrome/common/extensions/docs/toolstrip.html +++ b/chrome/common/extensions/docs/toolstrip.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/tut_debugging.html b/chrome/common/extensions/docs/tut_debugging.html index 21f1379..cfcfd8e 100644 --- a/chrome/common/extensions/docs/tut_debugging.html +++ b/chrome/common/extensions/docs/tut_debugging.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/tutorials.html b/chrome/common/extensions/docs/tutorials.html index 8180dd6..ab36fc7 100644 --- a/chrome/common/extensions/docs/tutorials.html +++ b/chrome/common/extensions/docs/tutorials.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/windows.html b/chrome/common/extensions/docs/windows.html index b848bd5..dd337c6 100644 --- a/chrome/common/extensions/docs/windows.html +++ b/chrome/common/extensions/docs/windows.html @@ -121,6 +121,7 @@ diff --git a/chrome/common/extensions/docs/xhr.html b/chrome/common/extensions/docs/xhr.html index 8b1916a..00ffecf 100644 --- a/chrome/common/extensions/docs/xhr.html +++ b/chrome/common/extensions/docs/xhr.html @@ -121,6 +121,7 @@ -- cgit v1.1