Jeremy-F
Jeremy-F

Reputation: 113

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

Upvotes: 1

Views: 2075

Answers (1)

Iván Nokonoko
Iván Nokonoko

Reputation: 5118

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.

Upvotes: 2

Related Questions