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

落花浮王杯 提交于 2019-12-13 05:19:21

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/31013559/chrome-extensions-variable-undefined-in-chrome-extension-even-though-it-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!