0

I've got a small problem. I want to read a var defined inside tag in DOM.

<script id="foo">
    var x = 1
</script>

I can access it via:

var script = document.querySelector("#foo");

But then what? Of course

var x_value = script.x

or

var x_value = script.outerHTML.x

doesn't work. So how can I get x's value then?

Thanks for your help!

Václav
  • 15
  • 1
  • 7
  • You can get the content of the tag, pass it to a JavaScript parser and traverse the AST to find what you want. However, that will of course not work if the value is computed dynamically. – Felix Kling Oct 25 '17 at 19:29

2 Answers2

0

Once you're within the scope you should be able to access your variable from wherever you want...

<script id="foo">
    var x = 1
</script>
<div id="test">
</div>
<script>
document.getElementById("test").innerHTML = x;
</script>
Derek Nolan
  • 744
  • 5
  • 11
0

Content script runs in isolated world so it cannot access the page variables directly.

  • a literal numeric value can be extracted with a regexp:

    var scriptText = document.getElementById('foo').textContent;
    var x = parseFloat(scriptText.match(/var x\s*=\s*(-?(\d*\.)?\d+(e-?\d+)?)|$/)[1]);
    
  • a global page variable of any JSON-ifiable type can be accessed from a script element because it runs in page context:

    function getPageVariable(name) {
      return new Promise(resolve => {
        window.addEventListener(`${chrome.runtime.id}-variable`, e => {
          resolve(JSON.parse(e.detail));
        }, {once: true});
        var script = document.createElement('script');
        document.documentElement.appendChild(script).text = `
          window.dispatchEvent(new CustomEvent('${chrome.runtime.id}-variable', {
            detail: JSON.stringify(window.${name})
          }))`;
        script.remove();
      });
    }  
    

    Usage:

    getPageVariable('x').then(x => {
      // do something with x
    });
    

    Depending on the page CSP, a different method of code injection may be required.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • I was hoping I could extract it from window object, something like `window.x`, but idk where that var is stored, it has to be somewhere though. – Václav Oct 25 '17 at 20:12
  • But it seems the second option works perfectly! Thank you very much! – Václav Oct 25 '17 at 20:16