Js Get Varible Defined In Script Tag (google Extension)
I've got a small problem. I want to read a var defined inside tag in DOM. I can access it via: var script = document.querySe
Solution 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:functiongetPageVariable(name) { returnnewPromise(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.
Solution 2:
Once you're within the scope you should be able to access your variable from wherever you want...
<scriptid="foo">var x = 1</script><divid="test"></div><script>document.getElementById("test").innerHTML = x;
</script>
Post a Comment for "Js Get Varible Defined In Script Tag (google Extension)"