我正在尝试开发一个适用于谷歌Chrome的扩展程序,但我遇到了一些问题,希望当用户点击图标时能够启动或创建一个新窗口。
就像这样:http://i.imgur.com/8iRkEOb.png 非常感谢!
就像这样:http://i.imgur.com/8iRkEOb.png 非常感谢!
首先,如果你的manifest中定义了default_popup
,你需要将其删除,因为它会干扰你想捕捉的点击事件。
接下来,你需要在后台脚本中捕捉该事件:
chrome.browserAction.onClicked.addListener(function(tab) {
// ...
});
接下来,如果我们想要一个窗口,可能需要查看 windows
API。 create()
看起来是你所需要的:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({/* options */});
});
您需要哪些选项?假设您想从您的扩展程序中打开一个页面,您需要使用 chrome.runtime.getURL
包装的 URL:
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")
});
});
然后,要像您展示的那样显示一个没有顶部工具栏的窗口,您需要使用窗口类型"popup"
:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.windows.create({
url: chrome.runtime.getURL("mypage.html"),
type: "popup"
});
});
最后,如果你想在窗口打开后执行一些操作,请使用回调函数:
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
});
});
chrome.tabs.create
而不是 chrome.windows.create
:) - deadcoder0904background.js
chrome.browserAction.onClicked.addListener(function(activeTab)
{
chrome.windows.create({ url: chrome.runtime.getURL("popup.html"), type:
"popup" });
});
manifest.json
{
"manifest_version": 2,
"name": "",
"description": "",
"version": "1.0",
"chrome_url_overrides": {
"newtab": "popup.html" //the html to show in popup
},
"browser_action": {
"default_icon": "img/zi.png" //some icon
},
"permissions": [
"tabs"
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
chrome.action.onClicked.addListener(tab => {
chrome.windows.create({
url: chrome.runtime.getURL("index.html"),
type: "popup" //No Address bar
//In here you can also add constrain for the window
//This is for manifest v3
})
});