Reputation: 1705
I am trying to inject some JS into a webpage using my Chrome extension's content script. The injected script declares a variable, which prints okay when printed from the same injected script. However, if I try to access the same variable later in the page or even in the console, it is not found. Please note that I am not declaring the variable in my content script, I am injecting JS in the actual webpage.
Here is the minimal code from content script:
var script = `<script>
var zzxx = "random stuff";
console.log(zzxx);
window.xyz = "1234";
console.log(window.xyz);
</script>`;
$('body').append(script);
Output:
random stuff
1234
But cannot access zzxx or window.xyz from console or another injected script. What's the reason?
Upvotes: 0
Views: 263
Reputation: 712
I believe that it should be an issue with variable range
To be sure try to replace
var zzxx = "random stuff";
with :
window.zzxx = "random stuff"
Edit this work for me :
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = "var toto = 3; console.log(toto);";
$("head").append(s);
Upvotes: 1