In my browser plugin I want to detect any use of a built-in JavaScript function. I override this function by injecting a piece of code onto the page. This code then triggers an event, and an event handler sends a message to my extension using chrome.runtime.sendMessage.

The problem is that now any page on the internet can also trigger the event and communicate with my extension. I want just my injected script to be able to communicate with my extension, to avoid a security problem such as with Grammarly.

How can I secure the communication between the injected script and the extension. I want to override a native JavaScript function, so I have to put script on the page (as opposed to the content script). Because it's on the page, I can't call chrome.runtime.sendMessage directly.

Edit: I thought of this solution: create a random secret key in the content script, and only handle events with that secret key. It feels like a total hack, so the question is still if there is a "right" way to do this.

  • i would change all copies of the string "messageListenerDetected" to securityToken from your 2nd example. That way, it's a different event name each time. maybe something alpha instead, like [].map.call(crypto.getRandomValues(new Uint16Array(10)), x=>x.toString(36)).join(""). does that onload event fire? you might call document.currentScript.remove() inside of overrideFunctions() so that other scripts can't possibly rip the token from the DOM (as it would all be sync execution and gone before they could), or if there's a way to call eval() on the site page, that would be even better. – dandavis Jul 31 '18 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.