我怎样才能先导航到不同的 href,然后让代码继续,只使用 JavaScript?

How can I navigate to a different href first, then let the code continue, using just JavaScript?

当我在 Chrome 浏览器的控制台中输入这段代码时,警告先出现,然后是新的 href,即使 'window.location.replace()' 在警告的前面:

window.location.replace('http://whosebug.com/');
alert('hi');

我想知道如何导航到新页面,然后让警报发生。我该怎么做?

I would like to know how to navigate to the new page, and then let the alert happen. How would i do that?

你不能。浏览器中的 JavaScript 环境与页面相关联。当页面被拆除时,环境也随之拆除。即使你要这样做:

// Example of something that DOESN'T work
window.location.replace('http://whosebug.com/');
setTimeout(function() {
    alert('hi');
}, 100);

...定时器回调永远不会触发,因为环境在它有机会触发之前就被拆除了。

您所能做的就是将信息传递到下一页,以便下一页上的代码运行。

我觉得@T.J克劳德的回答很好地掩盖了它,但我只是想强调他的最后一句话

All you can do is pass information to the next page so that code on that next page runs.

这当然只是暗示您将用户重定向到您拥有的位置(除非您拥有 Stack Overflow 而我不知道......),解决方案是传递 GET 参数,例如提醒您想要的消息,像这样

window.location.replace('http://whosebug.com/?msg=hi');

然后在另一个页面中,您将获得参数 msg 并简单地执行

alert(get_msg);

消息当然可以通过 GET 以外的其他方式传递(例如 POST),这也是大多数 "known" 框架处理其 "flash" 消息的方式(这是不再 JavaScript 相关)