Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify url in browser using javascript?

Tags:

javascript

Is it possible to change the url in the user's browser without actually loading a page, using javascript? I don't think it is (could lead to unwanted behavior), I'm in a situation where this would be convenient though:

I have a web app which displays reports generated by users. Layout roughly looks like:

-----------------------------------------------------------
 Column 1    |   Column 2
-----------------------------------------------------------
  Report A   |
  Report B   |  Currently selected report contents here.
  Report C   |

right now the user would be looking at a url like:

www.mysite.com/user123

To see the above page. When the user clicks the report names in column 1, I load the contents of that report in column 2 using ajax. This is convenient for the user, but the url in their browser remains unchanged.

The users want to copy the url for a report to share with friends, so I suppose I could provide a button to generate a url for them, but it would just be more convenient for them to have it already as the url in their browser, something like:

www.mysite.com/user123/reportb

the alternate is to not load the contents of the report in column 2 using ajax, but rather a full page refresh. This would at least have a linkable url ready for the user in their url bar, but not as convenient as using ajax.

Thanks

like image 964
user246114 Avatar asked Feb 26 '23 20:02

user246114


2 Answers

You can't change it in quite the way you asked for, but: The usual solution to this is to use window.location.hash, so the URL ends up being www.mysite.com/user123#reportb. Setting the hash doesn't cause a page load.

When the user's friend clicks the link, since the hash isn't sent to the server, you'll need to check it on load and do an ajax call (or what-have-you) to load the desired report.

This is (of course) the same mechanism anchors use, which you may or may not want to make use of. If not, make sure that the hashes you use don't match ids or anchor names in your page (and if so, of course, make sure they do).

like image 174
T.J. Crowder Avatar answered Mar 02 '23 17:03

T.J. Crowder


Look into using the JQuery history plugin. It allows for back/forward navigation on AJAX sites as well as bookmarking (think Facebook style navigation in the URLs) and you don't have to write your own code/handlers for the hashes.

http://plugins.jquery.com/project/history

like image 31
Tommy Avatar answered Mar 02 '23 15:03

Tommy