如何处理后退按钮同时改变了浏览器的URL与HTML5 pushState [英] How to handle back button while changing the browser-URL with HTML5 pushState

查看:234
本文介绍了如何处理后退按钮同时改变了浏览器的URL与HTML5 pushState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个页面的网站。当用户点击菜单按钮,内容满载阿贾克斯。 它工作正常。 为了提高搜索引擎优化,并允许用户复制/过去不同内容的URL,我使用

I’ve made a one page site. When user clicks on the menu buttons, content is loaded with ajax. It works fine. In order to improve SEO and to allow user to copy / past URL of different content, i use

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

它工作正常。 URL变化,浏览器不重新加载页面

It works fine. URL changes and the browser doesn’t reload the page

然而,当用户点击在浏览器的后退按钮,链接改变和内容必须被加载。

However, when user clicks on back button in browser, the url changes and the content have to be loaded.

我做这个和它的作品:

 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_();
        }
    };

你知道,如果有一种方法来改善这个code?

Do you know if there is a way to improve this code ?

推荐答案

我所做的就是在页面加载传递一个对象文本 pushState()。这样,您就可以随时回到你的第一次创建pushState。在我来说,我不得不推两次,我才回去。推进在页面加载一个国家帮了我。

What I did was passing an object literal to pushState() on page load. This way you can always go back to your first created pushState. In my case I had to push twice before I could go back. Pushing a state on page load helped me out.

HTML5允许你使用的数据属性,使你的触发器,你可以使用它们来绑定HTML数据。

HTML5 allows you to use data-attributes so for your triggers you can use those to bind HTML data.

我用一个尝试捕捉,因为我根本没有时间来找到一个polyfill旧版浏览器。您可能要检查Modernizr的,如果这是需要你的情况。

I use a try catch because I didn't had time to find a polyfill for older browsers. You might want to check Modernizr if this is needed in your case.

页面加载

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()触发。在我的情况下,委托,因为我已经在页面上的动态元素。

Bind the history.pushState() trigger. In my case a delegate since I have dynamic elements on the page.

// 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(),因为我的按钮是链接。

Bind the history.back() event to a custom button, link or something. I used .preventDefault() since my button is a link.

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

在弹出的历史回 - >检查一个按下的状态,除非它是第一次尝试

When history pops back -> check for a pushed state unless it was the first attempt

$(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)

无论我用这只不过是一个jQuery对象/函数,存储在里面的生活to

Wherever I've used this it's nothing more than a jQuery object/function, stored inside an IIFE.

请注意,我把这些脚本一起从我的实现结合一些想法,从最初的请求。所以希望这给你一些新的想法;)

Please note I put these scripts together from my implementation combined with some ideas from your initial request. So hopefully this gives you some new ideas ;)

这篇关于如何处理后退按钮同时改变了浏览器的URL与HTML5 pushState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆