Chrome Extensions Development Series 13: Messaging Message

Source: Internet
Author: User

Because content scripts runs in the context of a Web page, it's part of a Web page, not Google Chrome extensions. But content scripts often needs to communicate with other parts of the Google Chrome extension to share data.

This can be accomplished through messaging, which communicates with each other's listening and feedback messages. A message can contain any valid JSON object, such as Null,boolean,number,string,array,object.

1) One-time request and Response mode

For a one-time request and Response mode ,chrome.runtime.sendMessage(obj, function (response) {}) is from the content Scripts a request message to the Google Chrome Extensions page.

When sending a request message from the Google Chrome extensions page to content scripts, you need to give the ID of the current tab.

1 Chrome.tabs.query (2{active:true, Currentwindow:true}, 3     function(tabs) {4 Chrome.tabs.sendMessage (5Tabs[0].id,6{greeting: "Hello"}, 7             function(response) {8 Console.log (Response.farewell);9         });Ten});

When listening for messages, you need to register the messages you want to listen on.

 1  chrome.runtime.onmessage.addlistener (  2  function   (request, sender, Sendresponse) { 3  console.log (sender.tab? 4  from a content script: "+ Sender.tab.url:  5  from the extension );  6  if  (request.greeting = "Hello") //  Determines whether the message to be processed  7  Sendresponse ({ Farewell: "Goodbye"  8 }); 

Note: If more than one listener is registered for the same message, only the first listener can call the Sendresponse () method, and the other listeners are ignored.

2) maintain a long-term connection mode

For a mode that maintains long-term connectivity , you can process multiple messages by establishing a channel between the content scripts and the Chrome Extender page, which can be named for the channel. Each end of the channel has a Chrome.runtime.Port object that is used to send and receive messages.

In the content scripts actively establish the channel as follows:

1 varPort = Chrome.runtime.connect ({name: "Yisheng"});//Channel name2Port.postmessage ({joke: "Knock Knock"});//Send Message3Port.onMessage.addListener (function(msg) {//Listening Messages4   if(Msg.question = = "Who ' s there?"))5Port.postmessage ({answer: "Yisheng"});6   Else if(Msg.question = = "madame who?"))7Port.postmessage ({answer: "Madame ... Bovary "});8});

On the Google Chrome Extensions page, actively establish the following channels:

1 Chrome.tabs.query (2{active:true, Currentwindow:true}, 3     function(tabs) {4           varPort = Chrome.tabs.connect (//Establish a channel5Tabs[0].id,6{Name: "Yisheng"}//Channel name7         );8});

On the content scripts or Google Chrome Extensions page, listen for the following requests to establish a connection:

1Chrome.runtime.onConnect.addListener (function(port) {2Console.assert (Port.name = = "Yisheng");3Port.onMessage.addListener (function(msg) {4     if(Msg.joke = = "Knock Knock")5Port.postmessage ({question: "Who ' s there?")});6     Else if(Msg.answer = = "Madame")7Port.postmessage ({question: "Madame who?")});8     Else if(Msg.answer = = "Madame ... Bovary ")9Port.postmessage ({question: "I don ' t get it.")});Ten   }); One});

On either end of the content scripts or Google Chrome extensions page, call Chrome.runtime.Port.disconnect () to close the connection and start the Disconnect event. At this point, only the other end listens for the Chrome.runtime.Port.onDisconnect event, you can know that the connection is closed.

3) message mode between Google Chrome Extensions

You can also send messages between different Google Chrome extensions as long as you know the Google Chrome extension's ID. This allows Google Chrome extensions to publish services for other extensions.

The message between this Google Chrome Extender is also divided into one-time request and Response mode and a pattern for maintaining long-term connectivity .

The Google Chrome extension listens for messages that call its services as follows:

1 //One-time request and Response mode:2 Chrome.runtime.onMessageExternal.addListener (3   function(Request, sender, Sendresponse) {4     if(sender.id = = blacklistedextension)//blacklist5       return;//don ' t allow this extension access6     Else if(Request.gettargetdata)7 sendresponse ({targetdata:targetdata});8     Else if(request.activatelasers) {9       varSuccess =activatelasers ();Ten sendresponse ({activatelasers:success}); One     } A   }); -  - //mode to maintain long-term connectivity: theChrome.runtime.onConnectExternal.addListener (function(port) { -Port.onMessage.addListener (function(msg) { -     //See other examples for sample onMessage handlers. -   }); +});

The message to send the call service is as follows:

1 //The ID of the extension we want to talk to.2 varLaserextensionid = "ABCDEFGHIJKLMNOABCDEFHIJKLMNOABC";3 4 //Make a simple request:5Chrome.runtime.sendMessage (Laserextensionid, {gettargetdata:true},6   function(response) {7     if(Targetinrange (response.targetdata))8Chrome.runtime.sendMessage (Laserextensionid, {activatelasers:true});9   });Ten  One //Start a long-running conversation: A varPort =Chrome.runtime.connect (Laserextensionid); -Port.postmessage (...);

4) Google Chrome extension receives messages sent from a specified Web page

Google Chrome extensions can send and receive messages directly to some site-specific web pages.

First, set the range of Web pages that can communicate in the Google Chrome extension's Manifest.json file:

1 "externally_connectable": {2   "matches": ["*://*.example.com/*"]3  }

Second, the messages that listen to Web pages in Google Chrome extensions are as follows:

1 Chrome.runtime.onMessageExternal.addListener (2   function (Request, sender, Sendresponse) {3     if (Sender.url = = blacklistedwebsite) 4       return;  // don ' t allow the this web page access 5     if (Request.openurlineditor) 6       OpenUrl (request.openurlineditor); 7 });

Finally, in the specified Web page, send the following message:

1 //The ID of the extension we want to talk to.2 varEditorextensionid = "ABCDEFGHIJKLMNOABCDEFHIJKLMNOABC";3 4 //Make a simple request:5 Chrome.runtime.sendMessage (Editorextensionid, {openurlineditor:url},6   function(response) {7     if(!response.success)8 handleError (URL);9});

Chrome Extensions Development Series 13: Messaging Message

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.