我正在做一个Chrome扩展。单击popup.html中的按钮将打开一个新窗口并加载feedback-panel.html。
这是可行的,但是,在单击时,我想检查窗口是否已经打开,如果已经打开,请将焦点放在窗口上,而不是创建一个新的窗口。
JavaScript window.open only if the window does not already exist看起来很混乱,但它依赖于打开窗口时将打开的窗口作为变量存储在父页面上,并在打开新窗口之前检查这些变量。这对我来说行不通,因为父窗口(popup.html)经常会被关闭并重新打开,而我会丢失变量。
我尝试实现同样的想法,但是使用chrome.storage存储窗口变量,因为它允许您存储对象。好吧,它确实允许存储对象,但是它首先序列化对象,所以window变量失去了它的所有函数,最后我用
result.feedbackPanel.focus()不是函数
这里是我的尝试:
function openFeedbackPanel(){
chrome.storage.local.get('feedbackPanel', function (result) {
console.log( result.feedbackPanel); // logs window object sans all functions
if(result.feedbackPanel && ! result.feedbackPanel.closed){
try{
result.feedbackPanel.focus();
}
catch(error){
chrome.storage.local.remove('feedbackPanel', function () {
});
createFeedbackPanel();
}
}
else{
createFeedbackPanel();
}
});
}
function createFeedbackPanel(){
var win = window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
console.log(win); // logs full object as expected
chrome.storage.local.set({"feedbackPanel": win});
}
$('#some-button').click(openFeedbackPanel());所以,既然这是行不通的:
如何从非父窗口(未打开弹出窗口)检查弹出窗口是否已打开?
发布于 2016-03-15 00:55:40
不需要跟踪和存储窗口。
如果您知道扩展ID,最简单的方法是测试所有选项卡url,看看它是否已经打开
chrome.tabs.query({}, function(tabs) {
var doFlag = true;
for (var i=tabs.length-1; i>=0; i--) {
if (tabs[i].url === "chrome-extension://EXTENSION_ID/feedback-panel.html") {
//your popup is alive
doFlag = false;
chrome.tabs.update(tabs[i].id, {active: true}); //focus it
break;
}
}
if (doFlag) { //it didn't found anything, so create it
window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
}
});这里已经回答了如何获得extension ID,
发布于 2016-03-18 10:31:38
您还可以使用消息传递系统。这是一个扩展选项的示例。在onClick中为按钮调用如下函数:
// send message to the option tab to focus it.
// if not found, create it
showOptionsTab: function() {
chrome.runtime.sendMessage({window: 'highlight'}, null, function(response) {
if (!response) {
// no one listening
chrome.tabs.create({url: '../html/options.html'});
}
});
},在您的窗口/选项卡中,侦听以下消息
// listen for request to make ourselves highlighted
chrome.runtime.onMessage.addListener(t.onMessage);
...
// message: highlight ourselves and tell the sender we are here
t.onMessage = function(request, sender, response) {
if (request.window === 'highlight') {
chrome.tabs.getCurrent(function(t) {
chrome.tabs.update(t.id, {'highlighted': true});
});
response(JSON.stringify({message: 'OK'}));
}
};此方法的一个优点是它不需要选项卡权限。
https://stackoverflow.com/questions/36000099
复制相似问题