Javascript 是否可以捕获window.location.replace事件?
如果我当前在URLJavascript 是否可以捕获window.location.replace事件?,javascript,html,dom-events,hashchange,Javascript,Html,Dom Events,Hashchange,如果我当前在URL“example.com/somepage#somehash”上,并调用window.location.hash=“anotherhash”,则URL将更改为“example.com/somepage#anotherhash”。这将触发窗口。hashashchange事件 如果我当前在URL“example.com/somepage?a=1&b=two”上,并调用window.location.replace(“?one=1&two=2”),则URL将更改为“example.c
“example.com/somepage#somehash”
上,并调用window.location.hash=“anotherhash”
,则URL将更改为“example.com/somepage#anotherhash”
。这将触发窗口。hashashchange
事件
如果我当前在URL“example.com/somepage?a=1&b=two”
上,并调用window.location.replace(“?one=1&two=2”)
,则URL将更改为“example.com/somepage?one=1&two=2”
我读过这本书,但我找不到一本关于这场火灾的书
window.history.pushState是另一个选项,但据我所知,它也不会触发事件
编辑
我看了一下@Taki的答案。我创建了一个URL,因为当您转到完整页面视图时,可以看到URL的更改。但是,即使使用preventDefault
,页面仍在重新加载,卸载事件回调中发布到页面的信息消失的事实证明了这一点。因此,这不能用于客户端路由,这是我的目标
index.html
点击我
index.js
console.log(“index.js”);
$('myBtn')。在('click',函数(e)上
{
console.log(“单击按钮”)
窗。位置。替换(“?一=1,二=2”)
console.log(window.location.href);
});
$(窗口).on(“beforeunload”,函数(事件)
{
event.preventDefault();//只需暂停并查看cosdole
控制台日志(“卸载前”);
console.log(事件);
$(“#info”)。追加(“在卸载之前””;
console.log(window.location.href);//捕获url
});
不,没有这样的事件,检测类似事件何时发生的最简单方法是围绕历史设置代理
或者您可以重写它的方法。的作用类似于重定向,因此您可以侦听事件
Location.replace()方法将当前资源替换为
一个位于提供的URL
(不知道为什么它不能替换snippet:p中的窗口。位置
,但它可以在它之外工作)
document.querySelector('#myBtn').addEventListener('click',function()){
窗。位置。替换(“?一=1,二=2”)
});
addEventListener(“beforeunload”,函数(事件){
console.log(window.location.href);//捕获url
event.preventDefault();//只是暂停一下,看看吊牌
});代码>
点击我
谢谢。我玩过这个,我不确定它是否对我有用,因为它无论如何都会完全重新加载页面。但这是我的错,因为我没有说我想避免重新加载页面。更改哈希不会这样做。使用pushState
并触发自定义事件
,检查编辑。这就是解决问题的方法。虽然它不是一个自定义事件,而是另一个回调。这样我就不必胡闹了,我只需要使用散列而不是“?”来进行查询。不太传统,但代码更少。顺便说一句——这确实是一个简单定制事件的好例子。我还要玩一会儿。
<button id="myBtn">Click me</button>
<div id="info"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="index.js"></script>
console.log("index.js");
$('#myBtn').on('click', function(e)
{
console.log("button clicked")
window.location.replace("?one=1&two=2")
console.log(window.location.href);
});
$(window).on("beforeunload", function (event)
{
event.preventDefault(); // just to pause and see the cosdole
console.log("beforeunload");
console.log(event);
$('#info').append("<p>beforeunload</p>");
console.log(window.location.href); // capture the url
});