简体   繁体   中英

Chrome message extension : From injected script to background

/* My Background */
console.log("Init BackGround ! ");
chrome.runtime.onMessageExternal.addListener(
    (request, sender, sendResponse) => {
        console.log("J'ai bien reçu un truc");
        console.log(request);
        console.log(sender);
    }
);
    // Inject script
chrome.webNavigation.onCompleted.addListener((details) => {
    chrome.tabs.executeScript(details.tabId, {
        file: "include/ts/injectScript.js",
        runAt: "document_end"
    });
}, {url: [{urlPrefix: "https://website.com"}]});
console.log("End Background init");

/* My injected script */
    var extensionID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    chrome.runtime.sendMessage(extensionID, {test : 123},(response) => {
        console.log(response);
    });

/* One part of my manifest.json (with good url) */
"externally_connectable": {
    "matches": [
      "*://*.exemple.com/tests/*"
    ]
 },
 "permissions": [..., "*://*.exemple.com/tests/*",...]

The background automatically injects JS script at page load.

All tests performed in the console (on the current page) work, and the background is receiving messages.

Unfortunately, although the background well injects the script loading the page, it does not receive any messages.

Sorry for my english, Thank you in advance for your answers

Jérémy-F

You have to use chrome.runtime.onMessage.addListener instead of chrome.runtime.onMessageExternal.addListener to receive messages from your own content scripts.

chrome.runtime.onMessageExternal is for messages from other extensions/apps.

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