javascript 如何在 Google Chrome 扩展程序中启动新窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28799892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to launch a new window in Google Chrome Extension
提问by Richard
I'm trying to develop a Extension for Google Chrome, but I have some problems, I want to launch or create a new window when user click on it in the icon.
我正在尝试为 Google Chrome 开发一个扩展程序,但我遇到了一些问题,我想在用户单击图标时启动或创建一个新窗口。
Like this: http://i.imgur.com/8iRkEOb.png
像这样:http: //i.imgur.com/8iRkEOb.png
Thanks so much!
非常感谢!
回答by Xan
First off, if you have a default_popup
defined in the manifest - you need to remove it, as it interferes with the click event you want to catch.
首先,如果您default_popup
在清单中定义了一个 - 您需要将其删除,因为它会干扰您想要捕获的点击事件。
Then, you need to catch the event in a background script:
然后,您需要在后台脚本中捕获事件:
chrome.browserAction.onClicked.addListener(function(tab) {
// ...
});
Next, if we want a window, we probably want to look at the windows
API. create()
sounds like what you need:
接下来,如果我们想要一个窗口,我们可能想看看windows
API。create()
听起来像你需要的:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({/* options */});
});
What options do you need? Assuming you want to open a page from your extension, you'll need an URL wrapped in a chrome.runtime.getURL
:
您需要哪些选项?假设您想从扩展程序打开一个页面,您需要一个包含在 中的 URL chrome.runtime.getURL
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
// Just use the full URL if you need to open an external page
url: chrome.runtime.getURL("mypage.html")
});
});
Then, to show a window like you're showing, without top toolbar, you need a window type "popup"
:
然后,要显示一个没有顶部工具栏的窗口,您需要一个窗口类型"popup"
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
url: chrome.runtime.getURL("mypage.html"),
type: "popup"
});
});
Finally, if you want to do something after the window has opened, use the callback:
最后,如果你想在窗口打开后做一些事情,使用回调:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
url: chrome.runtime.getURL("mypage.html"),
type: "popup"
}, function(win) {
// win represents the Window object from windows API
// Do something after opening
});
});