简体   繁体   中英

Chrome extensions: variable undefined in chrome extension even though it exists in console

In my content scripts for my chrome extension, I dynamically load a external js file onto a html page once it is finished loading. This js file I load will define a variable called rfk . I have a set Interval for when rfk is defined, it will execute a script. However, even after succesfully loading the page, my content script will never find rfk to be defined, even though I can check through the browser console and find that rfk exists.

"content_scripts": [
    {
        "matches": ["*://www.att.com/*"],
        "js": ["att.js"],
        "run_at":"document_end"
    }
]

This is my code snippet in my att.js file:

alert('hey!');

document.body.style.backgroundColor="red";

var url="//product.reflektion.com/rfk/js/11165-52846072/init.js?cv=test&q="+(new Date).getTime()
, o = document, s = o.createElement("script");

s.type="text/javascript";
s.src=url;
o.getElementsByTagName("head")[0].appendChild(s);

var cE = setInterval(function(){
    rfk && (demo="instagram",rfk.P.fs.rw.extra_args={drsp:{_v:demo}},rfk.rebuild(),clearInterval(cE))
},100);

Isolated world problem.

Content scripts execute in a special environment called an isolated world . They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

Your content script will never see the variables defined by the page. And in the console you're (by default) looking at the page's context, not content script's context. You can switch that (in the <top frame> dropdown) to test.

You need to inject a page-level script to do anything with the page's own JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM