Chrome call function in content scripts from background.js

前端 未结 1 590
闹比i
闹比i 2021-01-02 03:13

I\'ve read the documentation but I still haven\'t been able to get this working.

Here is my manifest:

{
    \"name\":\"app\",
    \"version\":\"0.1\"         


        
相关标签:
1条回答
  • 2021-01-02 03:42

    To call a function in the content script from the background page, you first need to know the tab id. contextMenus.onClicked event has a tab parameter containing that id. Then use message passing to do it.

    For example, in your background page:

    chrome.contextMenus.onClicked.addListener(function(info, tab) {
      if (tab)
        chrome.tabs.sendMessage(tab.id, {args: ...}, function(response) {
          // ...
        });
    });
    

    In your content script:

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        sendResponse(myFunc(request.args));
    });
    
    0 讨论(0)
提交回复
热议问题