Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cope with refreshing page with JS History API pushState

Tags:

A small website I was creating (more like fiddling) uses AJAX to load each page. Previously I was changing the hash of the url, this worked great but was ugly, and the user could refresh the page, and it would stay on the same page.

Now I have switched to using pushState in the JS History API, which looks much better, and the back and forward work, but refreshing does not. For example:

Going to: http://example.com/page2 goes to a 404 as there is no real page called page 2. But if I click on the button which uses the pushState method to change the url, it works as it should.

How can allow refreshes, and permalinks with the new History API?

(And how do search engines treat this, seeing as Google had to create a way of indexing hash urls, by making the developer switch to #!, is it possible they will do something similar for the history api in the future?)

like image 210
Jonathan. Avatar asked May 09 '11 20:05

Jonathan.


People also ask

Does history pushState refresh the page?

The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page.

What is html5 pushState?

pushState() In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.


2 Answers

You shouldn't use pushState to push invalid URLs at all. It's meant to be used in cases where the site works both with and without AJAX - i.e. you push the URL which would result in the same output without AJAX when creating this output with AJAX.

If you want only virtual URLs (like in the pre-pushState era), keep using the hash tag.

like image 82
ThiefMaster Avatar answered Nov 15 '22 17:11

ThiefMaster


This is a somewhat old question, but it was one of the top google results. In the pursuit of being helpful, here is my solution.

You can use Apache's Mod_Rewrite to rewrite the url to a central location. For example: example.com/p2 gets its page content from example.com/index.php?page=p2 You can keep your current implementation of the History API and AJAX to get the content and include the following in your .htaccess

<ifModule mod_rewrite.c>   RewriteEngine On   RewriteRule ^([^/\.]+)/?$ index.php?page=$1&full=1 [L] </ifModule> 

In your index.php:

<?php   if(isset($_GET['full']) {     //Generate the full page here   }else{     //Generate just the content for AJAX   } ?> 

This Page is a good primer on using mod_rewrite to redirect an entire website. (Comments 11 & 13 have useful additions as well)

like image 21
Grexis Avatar answered Nov 15 '22 19:11

Grexis