Chrome Extension - Message from injected script to content script

992 views Asked by At

I've seen this type of question dozens of times: how can a chrome extension communicate with background script, content script, injected script, etc. The solution, as I understand it is to use window.postMessage or chrome.runtime.sendMessage, where appropriate.

 // Injected Script 
window.postMessage('Hello')

// Content Script
window.addEventListener('message', (message) => console.log(message))

Here is my problem, I want my injected script to send a message to my content script, which I've been able to accomplish. However, I don't want the website to see these messages (reasonably so, I know since the injected script is in the same context as the website, everything is shared).

The website that I'm modifying has multiple nested iframes and they use window.postMessage regularly to communicate. So when I send a message to my content script, from the injected script, using window.postMessage the original site sees the message, doesn't like it and alerts the end-user, via a pop-up. Since it's not my website that's beyond my control.

So what I'm looking for is a method to send a message directly to the content script, possibly using targetOrigin, but that doesn't seem to work.

Another solution is to create a custom event on the window of the injected script and send a message that way. It's 90% there but I need my content script to reply back, which I don't believe is possible with an event. I would need to fire a response from the content script using a new event. Didn't know if there was a better way.

0

There are 0 answers