简体   繁体   中英

Chrome extension – Trying to send messages between the background and a second content script(?)

I'm working on my first Chrome extension, it's all going well—you can see it here https://github.com/rowancavanagh/measure . The problem I'm writing about here isn't up on Github yet, though.

My extension's background script currently talks to an injected content script on any page you turn the extension on. That works fine.

What I'm trying to do now, though, is make an onboarding page (html) for first use of the extension. It gives a little intro sentence and then asks you to turn on the extension. At which point, I assumed I'd use the same chrome.tabs.sendMessage and chrome.runtime.onMessage that works for the background script and injected content script. Because it seems as though the background script sends a message out to the currently active tab, and any active script on that tab would be able to pick it up. Considering this doesn't work, I guess that's not the case.

In background.js , I've got the following message being transmitted when it turns on:

chrome.browserAction.onClicked.addListener(function(tab) {
    toggle = !toggle;
    if(toggle){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            tabId = tabs[0].id;
            chrome.tabs.sendMessage(tabId, {"whatToDo": "on"});
        });
    }
});

In a script loaded on to the onboarding's HTML page, I've got:

function testMeasure() {
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
        var whatToDo = message.whatToDo;
        if (whatToDo == "on") {
            console.log("Measure is on");
            dialogTwo.innerHTML = '<p>Now highlight some text</p>';
        };
    });
};

——

Update 24/2

testMeasure() is triggered and I get the following error:

Uncaught TypeError: Cannot read property 'addListener' of undefined

——

I've also tried to inject the script in the same way I inject the other content script in the extension, and that hasn't helped.

As I'm mainly a designer, my grasp of all this is pretty poor. So please explain in simple terms!

You just need to use chrome.runtime.sendMessage instead of chrome.tabs.sendMessage . The second one is for communicating with content scripts only.

Scripts loaded in extension pages are not content scripts, they have the same privileges as the ones for the background page.

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