JavaScript浏览器导航栏事件

Alp*_*a2k 5 html javascript jquery

我想阻止用户导航到不通过html元素访问的URL.例:

实际导航: myweb.com/news

我想myweb.com/news?article_id=10通过在浏览器导航栏中编写此内容来导航,以避免按任何元素(如<a>).

当用户myweb.com/news?article_id=10在浏览器URL中写入时,在他按下回车的那一刻,浏览器不应该允许他导航到该URL.

我试过了:

//This wont work since jquery does not support it
$(window.location.href).on('change', function() {
    //Here check if href contains '?'
    alert("Not allowed");
});

//Neither works, doesnt do anything
$(window).on('change', function() {
    alert("Not allowed");
});
Run Code Online (Sandbox Code Playgroud)

参考文献: 这里有类似问题On - window.location.hash - 更改?,但我对该问题的'参数'版本感兴趣.

Ioa*_*zan 1

尝试添加事件监听器:

window.addEventListener('popstate', function(event)
{
    var location = document.location;
    var state =  JSON.stringify(event.state);
});
Run Code Online (Sandbox Code Playgroud)

要检查 URL,最好的办法是将其与正则表达式进行匹配,例如:

if (url.match(/\?./)) {
  // do not allow access
}
Run Code Online (Sandbox Code Playgroud)

您可能需要扩展此设置,具体取决于您需要禁止访问的其他 URL。