因为弹出窗口关闭得太快,所以没有解决承诺问题 [英] Promise resolve not called because popup closes too fast

查看:72
本文介绍了因为弹出窗口关闭得太快,所以没有解决承诺问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  browser.windows.create({ url: urls }).then((newWindow) => {
    newWindow.tabs.slice(0, pins.length).map((tab, index) => {
      browser.tabs.update(tab.id, { pinned: true })
    })
  })

当我阻止弹出窗口(通过webdev工具)关闭但在正常使用情况下,解析不会触发时,效果很好.

It works great when I prevent the popup from closing (via webdev tools) but in a regular use case, the resolve is not triggered.

推荐答案

在我开始处理插件时,我也遇到了同样的问题(,您可以查看

I struggled with this same problem when I started working on my addon (In My Pocket for Firefox, you can have a look at the code on bitbucket if it can help, I implement exactly what I'm about to explain). I needed to trigger network calls to an API from the popup and do something when the request was succesful, and I got the exact same problem.

您要记住的是,只要打开弹出窗口,就会执行弹出窗口的代码.关闭弹出窗口就像关闭一个包含Javascript的网页:所有JS代码都已卸载",代码执行停止,没有更多的东西来处理已解决的Promise.

What you have to keep in mind is that code from a popup is executed as long as the popup is open. Closing the popup is like closing a webpage that contains Javascript: all its JS code is "unloaded", code execution stops, there's nothing more to handle the resolved promise.

一种避免这种情况的方法是在始终始终运行的后台脚本中实现实际行为,并通过

A way to circumvent this is to implement the actual behaviour in a background script that will always be running all the time, and communicate between the background script and the popup via messages, through the runtime.sendMessage method and an event listener setup with runtime.onMessage.addListener.

背景脚本是放置需要保持长期状态或执行长期操作的代码的地方,而与任何特定网页或浏览器窗口的生命周期无关.

Background scripts are the place to put code that needs to maintain long-term state, or perform long-term operations, independently of the lifetime of any particular web pages or browser windows.

您可能会喜欢消息(共享对象而不是纯字符串),但是您知道了.这样,即使在处理结束之前关闭了弹出窗口,仍无法立即解析的代码仍将一直处理直到完成.

You can get fancy with messages (sharing objects and not plain string) but you get the idea. And this way, your code that does not resolve immediately will still get processed all the way until it's finished, even if the popup is closed before the processing is over.

这篇关于因为弹出窗口关闭得太快,所以没有解决承诺问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆