Sending message to background script

前端 未结 1 1654
逝去的感伤
逝去的感伤 2020-11-27 20:45

I am trying to implement a screen sharing web application that will use the desktopCapture Chrome API to display the users screen on a web page. I have created the chrome e

相关标签:
1条回答
  • 2020-11-27 21:14

    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 */
        }
      );
      
    0 讨论(0)
提交回复
热议问题