问题
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