javascript - Can't access the window level variable even though it exists. returns undefined when accessed -
i trying access window level variable in script in window.onload()
, returns undefined
. when console log or try type in window
in debug console, shows me variable exists on window
object , has value. unclear why happening , there way access it? please correct me if doing wrong , point me in right direction. appreciated.
update: window._vp
variable declared in script of live website , trying access particular variable using chrome extension.
my script:
window.onload = _ => { console.log("window._vp is:", window._vp); }
website script:
var _vp = {}; _vp['isdashavailable'] = false; //...
you can see behavior in following screenshot of dev tool console:
thank you.
i believe issue extensions isolated context, detailed in so post context isolation faced identical issue.
you should try following method quoted other answer:
method 2b: using function
for big chunk of code, quoting string not feasible. instead of using array, function can used, , stringified:
var actualcode = '(' + function() { // code executed in local scope. // example, following not overwrite global `alert` method var alert = null; // overwrite global variable, prefix `window`: window.alert = null; } + ')();'; var script = document.createelement('script'); script.textcontent = actualcode; (document.head||document.documentelement).appendchild(script); script.remove();
this method works, because + operator on strings , function converts objects string. if intend on using code more once, it's wise create function avoid code repetition. implementation might like:
function injectscript(func) { var actualcode = '(' + func + ')();' ... } injectscript(function() { alert("injected script"); });
note: since function serialized, original scope, , bound properties lost!
var scripttoinject = function() { console.log(typeof scripttoinject); }; injectscript(scripttoinject); // console output: "undefined"
Comments
Post a Comment