Call background function of Chrome extension from a site

前端 未结 3 1530
误落风尘
误落风尘 2020-12-08 05:29

I am looking for a function inside a webpage te activate a chrome extension.

Imagine that http://www.example.com/test.html contains:



        
3条回答
  •  醉酒成梦
    2020-12-08 06:18

    There is a builtin solution to Send messages from web pages to the extension

    mainfest.json

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

    Web page:

    // The ID of the extension we want to talk to.
    var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
    
    // Make a simple request:
    chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
      function(response) {
        if (!response.success)
          handleError(url);
      });
    

    Extension's background script:

    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if (sender.url == blacklistedWebsite)
          return;  // don't allow this web page access
        if (request.openUrlInEditor)
          openUrl(request.openUrlInEditor);
      });
    

提交回复
热议问题