简体   繁体   English

使用JavaScript背景脚本关闭窗口? (Firefox扩展程序)

[英]Close window with JavaScript background script? (Firefox Extension)

I am currently writing a Firefox extension that opens a new window in my background script. 我目前正在编写Firefox扩展程序,该扩展程序在后台脚本中打开一个新窗口。 When a user clicks a button on a page the background script executes and opens the window. 当用户单击页面上的按钮时,背景脚本将执行并打开窗口。

So far I have: 到目前为止,我有:

// content script
downloadMod(linkToOpen); //button clicked
function downloadMod(url) {
    // var test = window.open(url, '_blank');
    var myPort = browser.runtime.connect({ name: "cac410c4672fff93bf0d3186636d8876de3dfeb6@temporary-addon"});
    myPort.postMessage({ greeting: url });
}

In my background script (the script the above code connects too) I have: 在我的后台脚本中(上面的代码也连接了该脚本),我有:

//background script
portFromCS.onMessage.addListener(function (m) {
        var test = browser.windows.create({
            url: m.greeting,
            allowScriptsToClose: true,
        });

NOTE: all the code works as expected. 注意:所有代码均按预期工作。 However, the trouble comes when closing the window. 但是,关闭窗口会带来麻烦。

I have tried variations of self.close() , window.close() . 我尝试了self.close()window.close()的变体 I even created a function to wait 5 seconds to load the newly created window and then close the page to no avail. 我什至创建了一个函数,等待5秒钟以加载新创建的窗口,然后关闭该页面无济于事。 All of my attempts come back with the error: 我所有的尝试都返回了错误:

Scripts may not close windows that were not opened by script. 脚本可能无法关闭脚本未打开的窗口。

I thought this error was supposed to be removed with the allowScriptsToClose flag? 我认为应该使用allowScriptsToClose标志删除此错误?

To close a window you created with browser.windows.create, you need to use browser.windows.remove. 要关闭使用browser.windows.create创建的窗口,需要使用browser.windows.remove。

So: 所以:

let windowId;

browser.windows.create({url: "http://google.be"}).then((data) => {
    windowId = data.id;
});

// Sometime later, use windowId to close the window
setTimeout(function(){
    browser.windows.remove(windowId);
}, 5000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM