Answer the question
In order to leave comments, you need to log in
How to pass messages from the page to the content script and vice versa?
Tell me, what is the easiest way to establish communication between the JavaScript code from the content script and the JavaScript code from the site page? How to pass messages between them WITHOUT using a background extension process as an intermediary?
My problem is that calling Chrome API methods only works from the context of the content script, but I would like to be able to call these methods from the code inserted on the page, and for this you need to somehow interact with it.
PS I don't need code examples, a hint will be enough for me to understand the possible implementation options.
Answer the question
In order to leave comments, you need to log in
So the content script is part of the extension. So it's impossible not to use it. Therefore, only through messages.
var port = chrome.runtime.connect();
window.addEventListener("message", function(event) {
if (event.source != window) return;
if (event.data.type == "FROM_PAGE") {
console.log("Получено сообщение от страницы: " + event.data.text);
port.postMessage(event.data.text);
}
}, false);
document.getElementById("theButton").addEventListener("click",
function() {
window.postMessage({ type:"FROM_PAGE", text:"Сообщение со страницы!" },"*");
}, false);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question