I want to send message from the console of the random web page to my chrome extension. chrome.extension.sendMessage doesn't seem to work.
According to the official docs you should use postMessage
in the sender and message
event listener in the receiver.
Here is an example:
Your website's page.html
var data = { type: "FROM_PAGE", text: "Hello from the webpage!" };
window.postMessage(data, "*");
Content script: (injected using chrome.tabs.executeScript(tabid, {code:...
)
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_PAGE")) {
console.log("Content script received message: " + event.data.text);
}
});
Here page.html
(which is not a part of the extension) posts messages to itself, which are intercepted and inspected by the content script. The reverse is possible through similar means.
To pass from content script to extension, you will have to use one of the available message-passing techniques.
It looks complicated and it is somewhat complicated but all this mumbo-jumbo is very secure.