2012-10-22 44 views
0

我目前正在创建一个Chrome扩展。但Google官方不允许该扩展程序访问网页中定义的变量或函数:它是允许的Chrome扩展通过内容阅读页面脚本内容脚本

但是,内容脚本有一些限制。他们不能:

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 

UPDATE:

在页面有像许多脚本标记:

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

有什么办法,我可以阅读$的配置和功能getConfig( )从内容脚本?或者这是不可能的?

谢谢!

回答

2

正如你可能注意到的chrome。* API只能被背景页面或其他插件特定的页面使用。内容脚本另一方面可以访问该页面,但不能使用chrome。* API。

您需要做的是使用Content Extension访问您想要的页面上的任何内容,然后将数据发送回后台页面。后台页面可以使用数据和chrome。* API。

该文档在内容脚本和后台页面之间有消息传递的很好的示例和文档。

http://developer.chrome.com/extensions/messaging.html

UPDATE

只能发送包含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"}); 
    }); 
+0

感谢爱德华多,WH我需要的只是读取页面变量和函数。我现在知道如何与内容脚本与后台页面通信。但我不知道我能用你提供的介绍做什么:( –

+0

他们目前唯一的解决方案是转移document.scripts和分析字符串,但是如果页面改变了某些东西,它就太难处理和不稳定 –

+0

所以也许你应该在你的问题中包含了一个具体的例子@AwQiruiGuo – Eduardo

相关问题