在脚本标记(Google扩展)中定义的JS获取变量 [英] JS get varible defined in script tag (Google Extension)
本文介绍了在脚本标记(Google扩展)中定义的JS获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小问题.我想读取DOM中标记内定义的var.
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");
那又如何呢?当然了
var x_value = script.x
或
var x_value = script.outerHTML.x
不起作用.那我怎么才能得到x的值呢?
doesn't work. So how can I get x's value then?
感谢您的帮助!
推荐答案
内容脚本在孤立的世界,因此它无法直接访问页面变量.
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();
});
}
用法:
getPageVariable('x').then(x => {
// do something with x
});
取决于页面CSP,可能需要不同的代码注入方法.
Depending on the page CSP, a different method of code injection may be required.
这篇关于在脚本标记(Google扩展)中定义的JS获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文