使用 X 关闭 Chrome 应用程序时 onClosed() 未触发

onClosed() not firing when using the X to close a Chrome App

Background.js:

chrome.app.runtime.onLaunched.addListener(function() {
  console.log('launched');
  chrome.app.window.create('index.html', {
    innerBounds: {
      width: 800,
      height: 600,
      minWidth: 200,
      minHeight: 200,
    }
  });
})

chrome.app.window.onClosed.addListener(function() {
    console.log('close bg');
});

mainfest.json:

{
  "name": "xxx",
  "description": "xxx",
  "version": "3.4.0",
  "manifest_version": 2,
  "icons": {
    "16": "16.png",
    "48": "48.png",
    "128": "128.png"
  },
  "permissions": [
    {"socket": [
      "tcp-listen:*:*", 
      "tcp-connect", 
      "resolve-host", 
      "udp-bind:*:*", 
      "udp-send-to:*:*"
    ]}
  ],

  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  }
}

当用户使用红色 X 时,我正在尝试检测 Chrome 应用程序 window 的关闭。但是,'close bg' 控制台日志从未出现,所以我采取因为它不会开火。

我错过了什么?


我更新了我的 .json 以包含一个持久的背景页面。我想也许 bg 页面正在快速关闭以触发事件。

{
  "name": "xxx",
  "description": "xxx": "3.4.0",
  "manifest_version": 2,
  "icons": {
    "16": "16.png",
    "48": "48.png",
    "128": "128.png"
  },
  "permissions": [
    {"socket": [
      "tcp-listen:*:*", 
      "tcp-connect", 
      "resolve-host", 
      "udp-bind:*:*", 
      "udp-send-to:*:*"
    ]}
  ],

  "app": {
    "background": {
      "page": "background.html",
      "persistent": true
    }
  }
}

我已经添加了以下用户的 "get" 想法:

chrome.app.runtime.onLaunched.addListener(function() {
  console.log('launched');
  chrome.app.window.create('index.html', {
      id:'cci',
    innerBounds: {
      width: 800,
      height: 600,
      minWidth: 200,
      minHeight: 200,
    }
  });
})


chrome.app.window.get('cci').onClosed.addListener(function() {
        console.log('close bg');
});

但是,在启动时出现此错误。我认为分配 ID 的速度不够快,因此 'cci' 无效。

"chrome.app.window.current().onClosed allows you to register an event listener for when a window is closed."

在这里找到答案: Close event for chrome.app.window

编辑: 文档:https://developer.chrome.com/apps/app_window#event-onClosed

状态:

Fired when the window is closed. Note, this should be listened to from a window other than the window being closed, for example from the background page. This is because the window being closed will be in the process of being torn down when the event is fired, which means not all APIs in the window's script context will be functional.

您需要将侦听器附加到特定的 window 才能正常工作,而不是附加到 chrome.app.window 全局对象。 chrome.app.window.create() 函数中的第三个参数允许您指定接收新创建的 window 对象作为参数的回调。

chrome.app.runtime.onLaunched.addListener(function() {
  console.log('launched');
  chrome.app.window.create('index.html', {
    innerBounds: {
      width: 800,
      height: 600,
      minWidth: 200,
      minHeight: 200,
    }
  }, function(window){
      window.onClosed.addListener(function() {
        console.log('close bg');
      });
  });
})