Sending message to background script

有些话、适合烂在心里 提交于 2019-11-26 20:57:12
Xan

You cannot simply use messaging the same way you would use it in a content script from an arbitrary webpage's code.

There are two guides available in the documentation for communicating with webpages, which correspond to two approaches: (externally_connectable) (custom events with a content script)

Suppose you want to allow http://example.com to send a message to your extension.

  1. You need to specifically whitelist that site in the manifest:

      "externally_connectable" : {
        matches: [ "http://example.com" ]
      },
    
  2. You need to obtain a permanent extension ID. Suppose the resulting ID is abcdefghijklmnoabcdefhijklmnoabc

  3. Your webpage needs to check it's allowed to send a message, then send it using the pre-defined ID:

    // Website code
    // This will only be true if some extension allowed the page to connect
    if(chrome && chrome.runtime && chrome.runtime.sendMessage) {
      chrome.runtime.sendMessage(
        "abcdefghijklmnoabcdefhijklmnoabc",
        {greeting: "yes"},
        onAccessApproved
      );
    }
    
  4. Your extension needs to listen to external messages and probably also check their origin:

    // Extension's background code
    chrome.runtime.onMessageExternal.addListener(
      function(request, sender, sendResponse) {
        if(!validate(request.sender)) // Check the URL with a custom function
          return;
        /* do work */
      }
    );
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!