Calling Content Script function on chrome.browserAction.onClicked

前端 未结 2 1877
余生分开走
余生分开走 2021-01-03 11:12

My question is fairly simple and I just want to figure out the easiest way to do this.

The current iteration of my chrome extension injects a DIV into the webpage w

相关标签:
2条回答
  • 2021-01-03 11:27

    devnull69 is correct, you need to use message passing. Also consider checking out chromeps. It's a small pubsub library I wrote for chrome extensions. Removes a lot of the overhead when writing message passing code.

    0 讨论(0)
  • 2021-01-03 11:31

    Yes, contacting a content script from a browser or page action button is done using messages sent back and forth between the background script and the content script(s)

    First step: Tell the background script what to do on browserAction/pageAction button click

    chrome.browserAction.onClicked.addListener(function(tab) {
       ...
    });
    

    Step 2: Inside the browserAction.onClicked event listener you can then send a message to the content script (in fact to any code listening!):

    chrome.tabs.sendMessage(tab.id, {<YOURMESSAGEPAYLOAD>});
    

    Step 3: Inside the content script, you add a listener for incoming messages

    chrome.runtime.onMessage.addListener(function(request, sender, callback) {
       // request contains the YOURMESSAGEPAYLOAD sent above as a Javascript object literal
    });
    

    You can also go the other way round and send messages from the content script to the background script by using the following inside the content script

    chrome.runtime.sendMessage({<YOURMESSAGEPAYLOAD>});
    

    and then use the onMessage listener inside the background script the same way as mentioned above.

    0 讨论(0)
提交回复
热议问题