Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension can not access custom window properties

Im trying to write a Chrome extension that has a dev tools panel. This extension needs to call functions defined on a property on window in a webpage that I also have made. In other words, the extension is only for my own web page and I control both. Example:

// This script is added in my own webpage application when it loads
window.myTest = () => { /* do something */ }

I want to be able to call the function window.myTest from my Chrome extension. I need to make similar functionality like https://github.com/zalmoxisus/redux-devtools-extension.

It seems that I need to do this by inject script/code from my backend page. I have all working, extension with backend page that gets invoked and I can see that the code that I inject gets called in the page context (testing by console.log gets written to the console output of the page).

Here is my code:

manifest.json

{
  "manifest_version": 2,

  "name": "MyTest",
  "description": "MyTest",
  "version": "0.0.1",

  "minimum_chrome_version": "10.0",

  "devtools_page": "devtools.html",

  "background": {
    "scripts": ["background.js"]
  },

  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["testscript.js"]
  }],

  "permissions": [
    "tabs",
    "<all_urls>"
  ]
}

testscript.js

window.myTest(); // myTest is undefined in the context of the injected script

background.js

// empty, but here to be able to open background page

I also have a pannel that sends a message to the background page when a button is clicked. I know that the panel and sending the message also work. But window.myTest is still undefined.

Edit Removed the injection from background.js, because I did not use it and have same issue as described.

like image 754
Martin Ingvar Kofoed Jensen Avatar asked Sep 06 '25 22:09

Martin Ingvar Kofoed Jensen


1 Answers

Finally, I got the specs on this. Mozilla and Chrome follow the same specs for extensions.

Content scripts get a "clean" view of the DOM. This means:

  • Content scripts cannot see JavaScript variables defined by page scripts.
  • If a page script redefines a built-in DOM property, the content script sees the original version of the property, not the redefined version.

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts

like image 130
Shyam Swaroop Avatar answered Sep 09 '25 23:09

Shyam Swaroop