简体   繁体   中英

chrome extension message from background.js to content.js with response, TypeError cannot read property

Hello I am new to chrome extensions and I'm trying to make a extension. I want the background.js to send a request to content.js every time the user goes to another tab and for that I have this code inside background.js

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

and in content.js I have this code to receive the request and send a response:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(request.greeting);
        var protocol = window.location.protocol;
        sendResponse({ proto: protocol });
    }
);

I get this error in the background console:

Error in event handler for (unknown): TypeError: Cannot read property 'proto' of undefined
    at background.js:6:32

and I get no error in the normal console. I have used this documentation:

https://developer.chrome.com/apps/messaging

and

https://developer.chrome.com/extensions/tabs#event-onActivated

What am I doing wrong?

content.js only runs in tabs whose url defined in the manifest.json file. if the url of the active tab does not match these urls ,the background.js gets none.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM