如何在使用HTML5 pushState更改浏览器URL时处理后退按钮

时间:2013-11-23 00:29:03

标签: javascript ajax html5 browser-history pushstate

我创建了一个单页网站。当用户单击菜单按钮时,内容将加载ajax。 它工作正常。 为了改善SEO并允许用户复制/过去不同内容的URL,我使用

function show_content() {
        // change URL in browser bar)
        window.history.pushState("", "Content", "/content.php");
        // ajax
        $content.load("ajax/content.php?id="+id);
}

工作正常。 URL更改,浏览器不会重新加载页面

但是,当用户点击浏览器中的后退按钮时,网址会发生变化并且必须加载内容。

我已经完成了这项工作并且有效:

 window.onpopstate = function(event) {
        if (document.location.pathname == '/4-content.php') {
            show_content_1();
        }
        else if (document.location.pathname == '/1-content.php') {
            show_content_2();
        }
        else if (document.location.pathname == '/6-content.php') {
            show_content_();
        }
    };

您知道是否有办法改进此代码?

1 个答案:

答案 0 :(得分:10)

我所做的是在页面加载时将对象文字传递给pushState()。这样,您始终可以返回到第一个创建的pushState。在我的情况下,我必须先推两次才能回去。在页面加载上推送状态帮助了我。

HTML5允许您使用数据属性,因此对于您的触发器,您可以使用它们来绑定HTML数据。

我使用try catch,因为我没有时间为旧浏览器找到polyfill。如果您的情况需要,可能需要检查Modernizr。

<强>页面加载

try {
    window.history.pushState({
        url: '',
        id: this.content.data("id"), // html data-id
        label: this.content.data("label") // html data-label
    }, "just content or your label variable", window.location.href);
} catch (e) {
    console.log(e);
}

事件处理程序

填充默认信息的对象

var obj = {
    url: settings.assetsPath, // this came from php
    lang: settings.language, // this came from php
    historyData: {}
};

绑定history.pushState()触发器。在我的情况下是一个委托,因为我在页面上有动态元素。

// click a trigger -> push state
this.root.on("click", ".cssSelector", function (ev) {
    var path = [],
        urlChunk = document.location.pathname; // to follow your example

    // some data-attributes you need? like id or label
    // override obj.historyData
    obj.historyData.id = $(ev.currentTarget).data("id");

    // create a relative path for security reasons
    path.push("..", obj.lang, label, urlChunk);
    path = path.join("/");

    // attempt to push a state
    try {
        window.history.pushState(obj.historyData, label, path);
        this.back.fadeIn();
        this.showContent(obj.historyData.id);
    } catch (e) {
        console.log(e);
    }
});

history.back()事件绑定到自定义按钮,链接或其他内容。 我使用了.preventDefault(),因为我的按钮是一个链接。

// click back arrow -> history
this.back.on("click", function (ev) {
    ev.preventDefault();
    window.history.back();
});

当历史回归时 - &gt;除非是第一次尝试,否则检查推送状态

$(window).on("popstate", function (ev) {
    var originalState = ev.originalEvent.state || obj.historyData;
    if (!originalState) {
        // no history, hide the back button or something
        this.back.fadeOut();
        return;
    } else {
        // do something
        this.showContent(obj.historyData.id);
    }
});

使用对象文字作为参数可以方便地传递你的id。然后,您可以使用一个函数showContent(id)

无论我在哪里使用this,它只不过是一个存储在IIFE内的jQuery对象/函数。

请注意我将这些脚本放在我的实现中,并结合您初始请求中的一些想法。所以希望这会给你一些新的想法;)