Can I change the URL string in the address bar using javascript - javascript

I've a link on my webpage, say 'about'. Clicking on it loads a particular div without refreshing the whole page using jquery .load(). This does not change the URL string in the browser address bar.
The same page can be accessed by going to www.mydomain.com/?page=about.
So what I want to do is, when the user clicks on the 'about' link, the pages will be loaded as it is (using jquery), but I want to change the URL string in the browser address bar also so that someone can actually copy or bookmark the exact page.
Is it possible to do so??

You have two possibilites to tackle this problem:
In newer browsers you can make use of the HTML5 history API, which lets change part of the URL, also the query string (and path afaik).
In browsers which don't support this, you can only change the fragment identifier # without reloading the page (via the location object). That means you have to change the URL to e.g.
www.mydomain.com/#!page=about
#! is a convention from Google to make Ajax sites crawlable. As the fragment identifier is not sent to the server, you have to detect it with JavaScript and load the corresponding data from the server.
There are jQuery plugins that help you to handler this.
I would look for a good plugin makes use of the history API if available and falls back to the hash based solution.
As written in my comment, you can also find more information here:
How to change browser address bar without reloading page, especially #ThiefMaster's answer.

Yes, I've done it by doing
location.hash = 'foo';
There's other attributes of location you can change, not sure what it's called for '?', probably query-string, get, or soemthing like that.

Related

How to use the URL filepath as parameters in plain html/javascript?

I know about setting and getting URL parameters, e.g. example.com/index.html?x=foo&y=bar&z=hello would give your javascript access to the x, y, and z variables specified in the URL.
What I wish for is the same behavior but utilizing the file path part of the URL. E.g. example.com/index.html/foo/bar/hello.
How can I accomplish this? In particular,
How can I make sure the browser knows to go to index.html even though the file path index.html/foo/bar/hello was specified?
How can I update the URL to example.com/index.html/foo/bar/world, such that if I press "Back" on the browser, it will go back to example.com/index.html/foo/bar/hello.
Furthermore, I'd heavily prefer if the solution was in pure javascript/html, without reliance on jquery or any other libraries.
There's 2 scenarios you should handle.
What if the user is on a foreign page and wants to visit your page using the link example.com/index.html/foo/bar? This should be handled on the server not on the client side.
If the user is already on some page, say example.com/index.html and wants to go to example.com/index.html/foo/bar, you may use the pushState method. You may look at https://developer.mozilla.org/en-US/docs/Web/API/History/pushState to change the current URL & and this https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate to do something when the user presses the back button.

Modify current URL (Gatsby / Reach Router)

Question: Is it possible to modify the current URL that's shown in browser's address bar and browser history?
To be specific, I only want to modify the URL that is visible to the user; I don't want to trigger navigation. (I have a Gatsby app, and Gatsby is using Reach Router.)
Motivation: I have a gallery of images that the user can click and navigate to URL such as /images/?id=52. The advantage of this approach is that /images/ can be prefetched to enable instant rendering of the page. However, this scheme is unfriendly to users who have disabled JS, as they will see no images at all when they navigate with query parameters. So I have also prerendered pages like /images/52/ that work without JS. So what I want to do is navigate the JS users with query parameters, but then modify the URL that they see to a URL that can be shared with anyone including non JS users.
What I think you're looking for is either window.location.replace() or window.location.assign()
Replace is merely visual, so if the user were to copy the URL to share with their friends you can manipulate that url that they see and copy.
Assign loads a new document, as if the URL you passed it is the one that got the document.
https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
Edit: a comparison
Difference between window.location.assign() and window.location.replace()
I believe you'll need to create a NodeJs server to handle this sort of action. It can take a query parameter from the URL ('images/?id=52') and then return the user to the URL 'images/52'.
Or you may be able to use the 'gatsby-source-filesystem' package.

How to change browser url without changing anything in history

You might think this is a duplicate, but it's not. I've seen the other SO answers about changing the browser url with replaceState() but I have a problem...
On one webpage on my website, it receives a lot of parameters, so the link goes on and on and on... I did replaceState(), and it shortened the URL by a lot. That worked. If I go on another link, and I go back in history, the URL will still be the same that I defined on replaceState() and the page gives a 404 error. Is there a way to just load the link the way it is and then temporarily change the URL so the user doesn't see a huge link but the system uses the actual URL?
I'm using JSP, go ahead and give me answers in JavaScript, JQuery, or Java.
You could store the parameters in localstorage (ie a cookie) then have your next page un-pick them from localstorage, thus reducing the size needed of the URL in the frst place. Example code (stolen from Storing Objects in HTML5 localStorage) :
// add to storage
localStorage.setItem('myAttibute', 'acceptable');
// Retrieve the object from storage (on another page)
var sMyAttibute= localStorage.getItem('myAttibute');
alert("myAttibute=" + sMyAttibute);
Hopefully it'll tell you that my attribute is acceptable.

How to grab referrer from a redirect using JavaScript?

I know that I can find out the referrer using:
document.referrer;
However, I have a one page website, and a redirection set to send all other pages in that website to the home page. I would like to have a way of capturing the link that originated the redirection. In this case, document.referrer is always empty.
So I guess, I need to know:
How do I set a referrer parameter before the redirection?
How do I capture that parameter with JavaScript in the home page?
You could pass it along in a URL parameter. For example, Google does something similar when you click a search result; the browser actually goes to google.com/url?url=https%3A%2F%2Fthe-site-you-want.com.
So you could redirect your users to 'http://your-site.com/?referrer='+ encodeURIComponent(document.referrer), and then once it hits the homepage, you can extract that value and run decodeURIComponent.
encodeURIComponent is a method that makes a value safe to put in a URL. decodeURIComponent is the reverse process.
Alternatively, you could put it in a hash rather than the querystring, like 'http://your-site.com/#'+ encodeURIComponent(document.referrer). Several client-side routers use this. Although that may break the back button unless you spend more time learning about pushState. When Twitter first used twitter.com/#!/foo-bar as a URL scheme, it broke many things. But it may be useful to you.

Could a page display diferrent content if the URL hash changes?

How could a page display different content based on the URL hash?
I'm not talking about the browser scrolling down to display the anchored section, but something like JavaScript reacting to that hash and loading different content via AJAX.
Is this common or even probable?
Oh yes - it's becoming a common pattern to handle page-state-to-URL persistence when content is AJAX driven.
Javascript can access this value via window.location.hash. Once that's done, you can perform any actions based on the value of that hash
Show/hide nodes
Makes other AJAX calls
Change page titles or colors
Swap images
etc
Really, any DHTML effect.
This is occasionally done. Youtube uses hashes to link to specific timestamps within a video.
EDIT: I had assumed that you might have an issue where if the user goes up and manually edits the hash in the address bar, the page doesn't reload and even javascript will not know that it changed. I was wrong. I tried it on Youtube it works.
I just built a system to do this a few weeks ago
depeding on the browser you need to detect the hash, heres how to do that
// test all possible places hash could be on different browsers
if(window.location.hash){
hash = window.location.hash;
} else if (document.location.hash){
hash = document.location.hash;
} else if (location.hash){
hash = location.hash;
}
// some browsers start the hash with #, remove it for consistency
if(hash.substring(0,1) == '#'){
hash = hash.substring(1,hash.length);
}
Then handle the value of the hash variable to trigger page changes as you please.
for example:
http://www.example.com#pageA
if(hash = 'pageA'){
document.getElementById('mainContentDiv').innerHTML = '<p> content for the page displayed when the hash sais pageA</p>';
}
Sammy is a javascript library that does just this.
As JavaScript has access to the URL-string it could of course act differently on the contents of the url.
I've occassionally seen something like this but I don't think that this is a good way to react unless in very specific uses.
One of the uses I remember was TiddlyWiki using the after-portion of the hash to set preferences for the page rendering and such.
It is fairly common among AJAX-heavy applications (think Gmail) to be able to have all the AJAXy stuff while still making it possible for you to bookmark a particular page or link someone to a particular page. If they didn't do this, it would be considered bad for usability. It is fairly easy to get the URL hash by doing window.location.hash - so you can then have a switch-like statement on page load to execute a particular set of Javascript functions if a hash is present.
Some jQuery plugins that achieve this functionality: history/remote, history.
The answer for this question will be more or less the same as my answers for these questions:
How to show Ajax requests in URL?
How does Gmail handle back/forward in rich JavaScript?
In summary, two projects that you'll probably want to look at which explain the whole hashchange process and using it with ajax are:
jQuery History (using hashes to manage your pages state and bind to changes to update your page).
jQuery Ajaxy (ajax extension for jQuery History, to allow for complete ajax websites while being completely unobtrusive and gracefully degradable).

Categories

Resources