gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:13:27 25 4
gpt4 key购买 nike

我有一个基本的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com