Viv*_*R K 6 html javascript google-chrome-extension
我在.js文件中定义了一个全局对象.例如,file1.js包含全局对象SomeObject.此文件在background.html中加载.
由于file1.js包含在background.html中,因此我可以访问此页面中的全局对象.所以这里没有问题.
当执行诸如单击扩展按钮之类的事件时,我正在使用chrome.tabs.executeScript(null, {file: "contentscript.js"});
api 运行内容脚本.
在这种情况下,如何访问脚本中的SomeObject?
Rob*_*b W 20
有没有办法让直接访问从一到后台网页的全局对象的内容脚本或注入脚本.
要从注入的脚本中使用背景页面的方法,请按照下列步骤操作:
chrome.runtime.sendMessage
从后台示例2请求功能.chrome.runtime.onMessage
.chrome.tabs.executeScript(tab.id, func)
.要从内容脚本使用背景页面的方法,只需要步骤3和4.
这是一个示例,其中内容脚本与后台页面通信:
// Example background page
function some_method(arg_name) {
return localStorage.getItem(arg_name);
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.type == 'localStorage - step 4') {
callback( some_method(request.name) );
} else if (request.type == 'localStorage - step 5') {
localStorage.setItem(request.name, request.value);
}
});
// Example contentscript.js
chrome.runtime.sendMessage({
type: 'localStorage - step 4',
name: 'preference'
}, function(value) {
if (value === null) {
// Example: If no preference is set, set one:
chrome.runtime.sendMessage({
type: 'localStorage - step 5',
name: 'preference',
value: 'default'
});
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20471 次 |
最近记录: |