首页 > 解决方案 > 创建第一个窗口时 chrome.windows.onCreated.addListener() 未运行

问题描述

我希望窗口在首次创建窗口时提示用户。如果用户创建另一个新窗口(例如:将选项卡拉出窗口以创建自己的窗口,或再次单击 chrome 图标),我的代码会提示用户,但在创建第一个窗口时不会。为什么是这样?

后台脚本:

//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;

}

标签: javascriptgoogle-chromegoogle-chrome-extension

解决方案


推荐阅读