ashiso
ashiso

Reputation: 325

Message Passing between Chrome Extension and Content Script

I've read through the Message Passing Documentation and tried to utilize it in my code as follows:

contentscript.js:

var buttonEl = document.getElementById("activateBtn");

if (buttonEl) {
    buttonEl.addEventListener("click", function () {
        alert("activateBtn clicked! " + chrome.runtime.sendMessage);

        chrome.runtime.sendMessage({button: buttonEl});
    });
}

backgroundscript.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log("onMessage:", request);
});

The goal is to let the content script be injected into a page (specified in the manifest.json) and then run. The script is running just fine - the alert message get's displayed, but the message is not send. Or not received. Either way, that button holds an ID which I need to pass to my privileged background code someway.

When I run the code in the developer console of the extension I receive the message just fine - so the receiving end seems to work.

Any leads on the problem?

Thank you for you time. :)

Upvotes: 0

Views: 949

Answers (1)

BeardFist
BeardFist

Reputation: 8201

If you check the injected page's console, you should see something like

TypeError: Converting circular structure to JSON

This is because you are trying to pass an HTML object through JSON. Try passing just the ID of the button instead and see if it works then.

Upvotes: 2

Related Questions