首页 > 解决方案 > Javascript 在 window.popstate 上获取未定义的 URL

问题描述

我正在尝试从 php 页面获取内容。我有一个 fetch 调用 + 一个 history.pushState 在点击时触发,它们都工作正常,但是 window.popstate 在通过按下浏览器的后退按钮返回时返回错误。错误是,window.popstate 不知道返回时要获取的 url。

不幸的是,我不知道如何将正确的url变量传递给 window.popstate。

        // the code stripped fetch function
        var load = function(url){
            fetch(url, {
                method: "GET"
            }).then(function(response) {
                    response.text().then(function(text) {

                        // parsing and temporary placing fetched content into a fragment
                        var content = new DOMParser().parseFromString(text, "text/html"),
                        bodyPart = content.querySelector('main'),
                        fragmentElement = document.createDocumentFragment(),
                        tempElement = fragmentElement.appendChild(bodyPart);

                        // replacing the current content with the fragment
                        document.body.replaceChild(tempElement, document.querySelector('main')); 

                        // need to assign the fetch on click function again, otherwise it won't work on the dynamically added (the fetched) links
                        clickOnPJAXLink();

                    });
                });
            }

            // the click function if clicking on any link function to start fetching content
            var clickOnPJAXLink = function(url) {
                document.querySelectorAll('A').forEach(a => {
                    a.addEventListener('click', (e) => {
                        e.preventDefault();
                        var url = e.currentTarget.getAttribute("href");
                        load(url);                          
                        history.pushState(url, "sometitle", url);
                    });
                });
            }

            // load the function initially on the home page
            clickOnPJAXLink();

            // popstate for back button
            window.addEventListener('popstate', function (e) {
                var state = e.state;
                if (state !== null) {
                    load(url);
                    console.log(url)
                }
            });

window.popstate 返回错误,即var url未定义,因此当然无法获取之前(历史回溯)的内容。

非常感谢任何提示!

标签: javascriptfetchpopstate

解决方案


history.pushState 将数据对象作为第一个参数,而不是字符串-尝试 history.pushState({url:e.currentTarget.getAttribute("href")} 然后 e.state.url 将等于您要加载的 url。


推荐阅读