chrome.runtime.sendMessage not working as expected

后端 未结 1 434
盖世英雄少女心
盖世英雄少女心 2020-12-09 11:32

I am writing a Chrome plugin with a content script and a background script, and I am trying to make the two communicate.

In my content script, I am doing

<         


        
相关标签:
1条回答
  • 2020-12-09 12:08

    chrome.runtime.sendMessage / onMessage (and other related events/methods such as connect) were introduced in Chrome 26.

    If you want to write an extension which is compatible with Chrome 20 - 25, use chrome.extension.sendMessage.

    A way to achieve optimal compatibility is to define the chrome.runtime methods yourself. For example, run the following code before the rest of your code (background/content script):

    if (!chrome.runtime) {
        // Chrome 20-21
        chrome.runtime = chrome.extension;
    } else if(!chrome.runtime.onMessage) {
        // Chrome 22-25
        chrome.runtime.onMessage = chrome.extension.onMessage;
        chrome.runtime.sendMessage = chrome.extension.sendMessage;
        chrome.runtime.onConnect = chrome.extension.onConnect;
        chrome.runtime.connect = chrome.extension.connect;
    }
    

    Then you can just use the latest API format:

    // Bind event:
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        // Do something
    });
    
    // Send message:
    chrome.runtime.sendMessage({greeting: 'hello'});
    

    If you feel uncomfortable with modifying methods on the chrome.runtime object, you can use the following approach instead:

    var runtimeOrExtension = chrome.runtime && chrome.runtime.sendMessage ?
                             'runtime' : 'extension';
    
    // Bind event:
    chrome[runtimeOrExtension].onMessage.addListener(
      function(message, sender, sendResponse) {
        // Do something
    });
    
    // Send message:
    chrome[runtimeOrExtension].sendMessage({greeting: 'hello'});
    
    0 讨论(0)
提交回复
热议问题