我目前正在创建一个 Chrome 扩展程序。但 Google 官方不允许扩展程序访问网页中定义的变量或函数:
However, content scripts have some limitations. They cannot:
Use chrome.* APIs (except for parts of chrome.extension) Use variables or functions defined by their extension's pages Use variables or functions defined by web pages or by other content scripts
更新:
页面中有很多脚本标签,例如:
<script>...<script>
<script>...<script>
<script>...<script>
<script>
$config = {};
$config.a = 1;
$config.b = 5;
function getConfig() { ...
// some code return config;
}
</script>
<script>...<script>
<script>...<script>
有什么方法可以从内容脚本中读取 $config 和函数 getConfig() 吗?或者这根本不可能?
谢谢!
最佳答案
正如您可能注意到的那样,chrome.* API 只能由后台页面或其他插件特定页面使用。另一方面,内容脚本可以访问页面,但不能使用 chrome.* API。
您需要做的是使用内容扩展来访问页面上您想要的任何内容,然后将带有数据的消息发送回后台页面。然后,后台页面可以使用数据和 chrome.* API。
这些文档提供了有关内容脚本和后台页面之间消息传递的非常好的示例和文档。
http://developer.chrome.com/extensions/messaging.html
更新
您只能发送包含 JSON 对象的消息。换句话说,您无法发送 getConfig 函数。但您可以在示例中发送 $config 。如果 $config 对象不是 JSON,您需要以某种方式序列化它。
页面上的代码您无法控制
$config = {};
$config.a = 1;
$config.b = 5;
contentscript.js
function getConfig(){return $config;}
chrome.extension.sendMessage({type: 'config', content: getConfig()}, function(response) {
console.log(response.status);
});
background.js
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.type == "config") {
// DO SOMETHING WITH request.config here
sendResponse({status: "OK"});
}
sendResponse({status: "Unknown request type"});
});
关于javascript - Chrome扩展程序是否允许通过Content Script读取页面脚本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13007295/