JS get varible defined in script tag (Google Extension)

↘锁芯ラ 提交于 2020-01-06 05:02:27

问题


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!


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/46940616/js-get-varible-defined-in-script-tag-google-extension

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