在chrome扩展程序中,我正在通过background.js创建一个新的html页面作为弹出窗口。检查下面的background.js代码,
chrome.contextMenus.create({
title: "share this",
contexts: ["selection"],
onclick: myFunction
});
var test0 = "Testing content Outside the myfunction";
function myFunction(data) {
var theSelection = data.selectionText;
console.log(theSelection);
chrome.tabs.query({'active': true, "lastFocusedWindow":true}, function(tabs) {
var sourceURL = tabs[0].url;
chrome.windows.create({
url: chrome.runtime.getURL('redirect.html'), type: 'popup'},
function(tab)
{
});
return record;
})
}
我已经通过here获得了getbackgroundpage函数。我可以使用它访问变量test0但不能访问sourceURL(因为它不在窗口范围内)。
通过重定向弹出窗口代码如下,
var bg = chrome.extension.getBackgroundPage();
var sourceURL = bg.sourceURL;
var testvariable = bg.test0;
sourceURL未定义。
没有得到如何将变量定义为全局变量的线索,以便在弹出窗口中进行访问。
有没有更好的方法,我们可以做到吗?
答案 0 :(得分:-1)
老兄,尝试使用Gogle message passing。
之前的链接中的小例子
BackgroundScript
var myFunc = function(){
//some code
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.messageType == "callSomeFunc") {
myFunc();
sendResponse({
status: "Function myFunc called."
});
}
//use return true for async response
return true;
});
contentScript
chrome.runtime.sendMessage({
messageType: "callSomeFunc"
},
function(response) {
// response contain {status: "Function myFunc called."}
console.log(response);
});