Promise resolve not called because popup closes too fast

这一生的挚爱 提交于 2019-12-13 03:44:01

问题


I have the following piece of code:

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

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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/50782412/promise-resolve-not-called-because-popup-closes-too-fast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!