【问题标题】:history.pushstate for changing url without page load not workinghistory.pushstate 用于在没有页面加载的情况下更改 url 不起作用
【发布时间】:2020-01-21 12:25:33
【问题描述】:

我一直在尝试使用 history.pushState 在不更改 url 的情况下更改页面内容,但出现以下错误

index.html:164 未捕获的 DOMException:无法在“历史”上执行“pushState”:无法在文档中创建 URL 为“file:///home/Desktop/abc/selected=box2”的历史状态对象来源为“null”,URL 为“file:///home/Desktop/abc/index.html”。 在 HTMLAnchorElement。 (file:///home/unfactory/Desktop/abc/index.html:164:17)

HTML 代码

<span style="float:right;"><a href="#" class="box" id='box1'>Contact Us</a></span>
<span style="float:right;"><a class='box' id='box2'>Asia-Pacific&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></span>
<span style="float:right;"><a href="#top" class="box" id='box3'>Global&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a></span>    

js 代码

function selectBox(id) {
    boxes.forEach(b => {
        b.classList.toggle('selected', b.id === id);
    })
}

let boxes = Array.from(document.getElementsByClassName('box'));
console.log(boxes);
boxes.forEach(b => {
    let id = b.id;
    console.log(id);
    b.addEventListener('click', e => {
        history.pushState({ id }, `Selected:${id}`, `./selected=${id}`)
        selectBox(id);
    })
})

【问题讨论】:

  • 当您只是从文件系统加载 HTML 文件时,不要期望这样的东西能够正常工作。设置本地测试服务器,以便您可以通过 HTTP 正确访问它们。
  • 这是您尝试推送的有效 URL 吗?你的意思是file:///home/Desktop/abc/?selected=box2 吗? (注意查询参数)
  • 我很惊讶您收到该错误,而不是“操作不安全”错误。

标签: javascript


【解决方案1】:

似乎history.pushState 已被弃用,您需要使用history.push(url)

https://github.com/ReactTraining/react-router/issues/4049

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-10-28
  • 2020-10-04
  • 2013-07-07
  • 1970-01-01
  • 2020-04-20
  • 2012-06-02
  • 2013-06-21
相关资源
最近更新 更多