Javascript 创建第一个窗口时,chrome.windows.onCreated.addListener()未运行
我希望窗口在首次创建窗口时提示用户。如果用户创建了另一个新窗口(例如:从窗口中拉出一个选项卡以创建自己的窗口,或者第二次单击chrome图标),而不是在创建第一个窗口时,“我的代码”会提示用户。为什么会这样 背景脚本:Javascript 创建第一个窗口时,chrome.windows.onCreated.addListener()未运行,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我希望窗口在首次创建窗口时提示用户。如果用户创建了另一个新窗口(例如:从窗口中拉出一个选项卡以创建自己的窗口,或者第二次单击chrome图标),而不是在创建第一个窗口时,“我的代码”会提示用户。为什么会这样 背景脚本: //an array of current open windows. var windowArray = {}; //when a new window is created, start the creation of a new package. chrome.windo
//an array of current open windows.
var windowArray = {};
//when a new window is created, start the creation of a new package.
chrome.windows.onCreated.addListener(createWindowPackage);
//get current window's id
function getCurrentWinID(callback){
console.log("getCurrentWinID() called")
var windId;
chrome.windows.getCurrent(function(currentWin){
windId = currentWin.id;
//console.log("from getCurrentWinID(), windId = " + windId)
//*****unique window Id properly getting retrieved here
callback(windId);
});
}
//_______________________________________________________________________________________
//start the creation of a new 'windowPackage' object by prompting the user for a goal.
function createWindowPackage(){
var goal = prompt("What is your goal this browsing session?","E.g: To watch Daniel Schiffman's first video.");
var windId;
//getting the current window's id
getCurrentWinID(function(windId){
var winId = windId.toString();
//*****unique window id properly received here
//in the windowArray, have the windId key refer to a new windowPackage object.
windowArray[winId] = new windowPackage(goal, windId);
//*****so we've successfully created a new window package with this goal and a unique window Id
});
}
//_________________________________________________________________________________________
//a window package includes the window id and a tasks[] array
class windowPackage{
constructor(startTask, winId){
this.id = winId;//winId is a string right now.
this.tasks = [startTask];
this.goal = startTask;
this.isItOn = 1;
}
但是,在创建第一个新窗口时,上面的代码并不用于提示用户,但此代码确实有效:
//an array of current open windows.
var goal;
chrome.windows.onCreated.addListener(askGoal);
function askGoal(){
goal = prompt("What is your goal this browsing session?","E.g: To watch Daniel Schiffman's first video.");
isItOn = 1;
}
1) 如果我理解正确,第一个窗口是在任何扩展运行之前创建的主浏览器窗口(除非您指定后台权限并允许Chrome运行此类后台扩展)。2) chrome.windows.getCurrent没有做您认为的事情,请再次查看其描述,因此您只需使用传递给onCreated callback的参数,请参阅文档,您只需声明函数createWindowPackage({id:winId}),在manifest.json中将“背景”添加到“权限”中即可,谢谢:)