如何在浏览器页面被杀死后运行一个任务?

How to run a task after the page being killed in browser?

首先,它有两个页面:example.com/pageAexample.com/pageB,它不是SPA。

页面被history.back杀死后如何运行延迟任务?

我尝试使用setTimeout,但在history.back之后执行任务失败,因为timer在页面更改时将在堆栈中被清除。

var a = 1

function refresh() {
  // <p id="count"></p>
  count.innerText = a
}

function foo() {
  a += 1
  refresh()
}

// called in PageB
function goBackA() {
  setTimeout(foo, 1000)
  history.back()
}

PageA 中计数仍然是 1 而不是 2。

出于安全原因,浏览器永远不会支持您在页面被杀死后 运行 某些代码的目标,因为当某些代码可以 运行 在不同的页面上时,这是危险的。

一旦页面为reload/killed,所有未完成的任务将被清除,即使在SharedWorker

那么,有两种方法可以实现您的逻辑:

  1. 更改为 SPA
  2. 给另一个页面一个类似查询的提示