javascript - Chrome 应用 : Execute function defined in an app window from a background script

标签 javascript google-chrome google-chrome-app

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

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

...

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

...

背景.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并没有真正正确地显示如何附加这些事件:它们附加到窗口实例,例如

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

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

关于javascript - Chrome 应用 : Execute function defined in an app window from a background script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33098505/

相关文章:

javascript - 在浏览器控制台中键入时,var x=10 和 x=10 有什么区别?

google-chrome - 谷歌浏览器缓存问题

javascript - 如何创建包含自身页面的无限 Iframe?

css - 前后伪选择器在 chrome 中不起作用

java - 从现有 Java 项目创建 servlet

javascript - 传单中两条线的交点

javascript - Angular JS 从服务返回数据和 Http 回调方法

javascript - 使用 Bower 和 Highcharts Shim 的 Chrome 开发编辑器

android - 在 PhoneGap/Chrome 应用程序中存储视频以供离线使用

google-chrome-extension - 是否可以在 Chrome 网上应用店中进行部分推出?