Chrome 应用程序:从后台脚本执行应用程序 window 中定义的功能

Chrome App: Execute function defined in an app window from a background script

我有一个基本的 canvas 游戏作为 chrome 应用程序。当我最小化游戏 window 时,游戏继续自行运行。我想在 window 最小化时执行函数 pause()

index.js(通过 <script> 标签包含在 index.html 中)

...

function pause(){
  paused = true;
  pausebtn.classList.add('hidden');
  pausemenu.classList.remove('hidden');
}

...

background.js

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    'outerBounds': {
      'width': screen.availWidth,
      'height': screen.availHeight
    }
  });
});

我应该把 chrome.app.window.onMinimized.addListener() 放在哪里?

然后,从那里,我如何实际执行函数 pause()

我正在寻找类似的东西:

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    'outerBounds': {
      'width': screen.availWidth,
      'height': screen.availHeight
    }
  });
});
chrome.app.window.onMinimized.addListener(function(gamewindow){
  gamewindow.pause();
});

首先,the documentation 似乎并没有正确显示如何附加这些事件:它们附加到 window 个实例,例如

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    'outerBounds': {
      'width': screen.availWidth,
      'height': screen.availHeight
    }
  }, function(createdWindow) {
    createdWindow.onMinimized.addListener(function() {
      /* code goes here */
    });
  });
});

至少有三种可能的答案,一种是直接的,一种是多抽象层的,另一种是移动你的逻辑。

直接:

直接调用方法,使用contentWindow属性:

createdWindow.contentWindow.pause();

虽然这与代码紧密耦合:如果您重构应用程序代码,您也需要重构后台脚本。

抽象:

传递消息,然后在游戏中处理。

// background
chrome.runtime.sendMessage({pause: true});

// app window
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if(message.pause) {
    pause();
  }
});

移动逻辑:

您应用的脚本不是内容脚本。他们不受 API 访问限制,因此可以自己收听事件 - 这可能是最不尴尬的方法。

// app window
chrome.app.window.current().onMinimized.addListener(pause);

..是的,就是这样。比试图传递命令要干净得多。