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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:35:36  来源:igfitidea点击:

How to launch a new window in Google Chrome Extension

javascriptgoogle-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.pngenter image description here

像这样:http: //i.imgur.com/8iRkEOb.png在此处输入图片说明

Thanks so much!

非常感谢!

回答by Xan

First off, if you have a default_popupdefined 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 windowsAPI. create()sounds like what you need:

接下来,如果我们想要一个窗口,我们可能想看看windowsAPIcreate()听起来像你需要的:

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
  });
});