Simple message passing between 'background.js' to 'contentScript.js'

后端 未结 2 753
借酒劲吻你
借酒劲吻你 2021-01-19 07:25

I\'m trying to apply the following flow :

binding for keys in the background.js , when pressing them : Sending message from background.js -> c

相关标签:
2条回答
  • 2021-01-19 07:27

    You're trying to send messages from the background page to the content script. From the official documentation, you're using this code snippet to send messages from the background page:

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
     console.log(response.farewell);
    });
    

    However, the docs clearly mention that the code mentioned above is to send a message from a content script. This is the reason why you probably get the error:

    Error in event handler for (unknown): Cannot read property 'farewell' of undefined
    Stack trace: TypeError: Cannot read property 'farewell' of undefined
    

    What you want to achieve is sending a request from the extension (background page) to a content script which requires you to specify the tab in which the content script is present:

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
         console.log(response.farewell);
      });
    });
    

    I hope this clarifies things and gets you started in the right direction.

    0 讨论(0)
  • 2021-01-19 07:42

    There are 3 ways to Send Message in Chrome Extension, you can refer to Message Passing.

    Usually use one-time request, for example:

    In background.js

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {  
      chrome.tabs.sendMessage(tabs[0].id, {message: "hello"}, function(response) {
        console.log(response);
      }); 
    });
    

    In contentscripts.js

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
      console.log(request.message);
      if (request.message == "hello") {
        sendResponse({farewell: "goodbye"});
      }
    });
    
    0 讨论(0)
提交回复
热议问题