I need to pass a message (raise an event) in a Chrome extension, and have JavaScript on a web page react to it.
In content_script.js
of the extension, there should be a function like
raiseXYZevent(data);
JavaScript on the web page http://example.com/mypage.html
should execute a handler
function processXYZevent(data) { ... }
The problem is that content script within an extension cannot interact with JavaScript on the web page directly (it can only modify DOM). Is there a way to make DOM changes from the extension, somehow detect them from the web page and call processXYZevent
?
Type the url in the main input field and choose the method to use: GET/POST/PUT/DELETE/PATCH. Click on the arrow "Send" or press Ctrl+Enter. You'll see info about the response (time, size, type) and you'll be able to see the content response in the response section.
If you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified runtime. sendMessage or tabs. sendMessage. This lets you send a one-time JSON-serializable message from a content script to extension, or vice versa, respectively.
Click on Add to Chrome > Add Extension. Step 2: Open the website which has the protected text, click on the extension icon on the top right corner, and click on the Copyfish extension. Step 3: The extension provides you with a tool to select the area in which the text you want to copy is present.
Since the content script and the webpage share the same DOM, you can use postMessage
to send messages between them. The Chrome API documentation explains this in detail with examples.
From content script inject this:
$('html').append(`
<script>
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
if (event.data.type && (event.data.type == "FROM_CONTENT")) {
console.log("Page script received: " + event.data.text)
console.log(event.data.text) // "Something message here"
}
}, false)
<\/script>`)
In content script you can execute this:
window.postMessage({ type: "FROM_CONTENT", text: "Something message here"}, "*")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With