Chrome应用程序:从后台脚本执行在应用程序窗口中定义的函数

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

本文关键字:应用程序 窗口 定义 函数 执行 后台 脚本 Chrome      更新时间:2023-09-26

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

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

...
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();
});

首先,文档似乎没有真正正确地显示如何附加这些事件:它们附加到窗口实例,例如

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

. .是的,就是这样。