简体   繁体   中英

Chrome extensions communication (content scripts)

I got 2 extensions in Chrome, both only uses content scripts at the moment. Both extensions listen on websocket for messages from the server. Also they both get the same message "same" (obviously a minimal difference) time. After they got the message they both process it and at the end they both have a result which is an int number.

What I would like to do is sending this number from extension A to extension B and from ext. A to ext. B so they both have the other's result.

I've really tried to google a solution for this, but I couldn't find any. Also I would like to avoid sending the results back to the server and then back to the extensions again.

Is there any way (preferably only JS) to do this?

Thanks!

This has been discussed here: Can Chrome extensions communicate with each other?

you can use this api: https://developer.chrome.com/extensions/messaging#external

chrome.runtime.sendMessage(otherExtensionId, {msg: 'hello'},
  function(response) {
    if (response.msg='hi')
      chrome.runtime.sendMessage(otherExtensionId, {msg: 'how are you?'});
  });

and in the other extension:

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (request.msg=='hello') {
      sendResponse({msg: 'hi'});
    }else ifif (request.msg=='how are you?'){
      doSomething()
    }
});

also for another means of communication, you can create an invisible div inside your page, and have both extensions constantly checking if it's contents change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM