0

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?

Cashif Ilyas
  • 1,619
  • 2
  • 14
  • 22
  • Possible duplicate of [Insert code into the page context using a content script](https://stackoverflow.com/questions/9515704/insert-code-into-the-page-context-using-a-content-script) – wOxxOm Jan 24 '18 at 22:45

1 Answers1

1

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);
Sylvan LE DEUNFF
  • 682
  • 1
  • 6
  • 21