Prevent URL from showing using history.pushState - javascript

I am trying to create a navigation in the CMS I am building, but it seems that every problem I fix only gives me more problems.
I want to do the following:
User clicks on a link: http://cms.abayocms.dev/swatch-settings/?/site/1
The PHP script does not detect a '/swatch/'in the URL and creates a new swatch
Issue 1: The URL does not change after adding a swatch, and I can't use PHP to change the header, because that is already sent!
So when a user refreshes the page, a new swatch will be created, etc, etc.
I don't want that, so I added a step:
I added a new peace of code (javascript):
location.replace(window.location + '/swatch/' + newSwatchID);
Issue 2: This method refreshes the page. I just want to add it to the URL and not refresh it.
To prevent the above issue, I tried 'history.pushState' (if supported by the browser) and I added the following code:
history.pushState(null, null, window.location+'/swatch/'+newSwatchsetID);
Issue 3: This ADDS a history event, so when the user clicks the browsers 'back' button, he again ends up on the URL: http://cms.abayocms.dev/swatch-settings/?/site/1. Which AGAIN creates a new swatch.
Is there a way to prevent this?

If you want to update the current state than you have to use history.replaceState();
Just use history.replaceState(null, null, window.location+'/swatch/'+newSwatchsetID);
This wont add a new state on History object so history.back() will reload the previous page instead of a state object.

Related

How to go back to the previous page when browser back button is clicked in a webpage even when the hash is changed?

I have a web page in which my anchor tags refer to one of the elements within the same page using #id. But this changes my URL as it adds the #id into the suffix. So now when I want to go back to the page from where I came by clicking the back button of the browser, it doesn't go back to the previous page instead it goes back to the hash selections I have made by clicking the anchor tags. Please help me by giving a solution to this.
When you use a hash route it creates a new record in the browser history the same as if you navigated to a new page. So if you navigate on your site from a page to a hash route on that page, then navigate to a new page, you will have to click on the back button twice to get back to your original location.
So if you navigate https://example.com -> https://example.com#myHash -> https:/example.com/another-page then the first back button click will navigate to https://example.com#myHash and the second back button click will navigate to https://example.com
Hope that helps
You can use history.replaceState() function from History API to achieve such behavior. When user will click on anchor you will just replace current history item instead of adding a new one.
Edit: window.location.replace()
Another approach is to use window.location.replace() which is does not adds a new entry to browser's History:
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
So what can be done to achieve the desired result is to add an onclick handler on the body element with a logic inside which will replace current location if current location is not a homepage (or any other page). This handler will look similar to the code below:
function handler (event) {
if (!isAnchor(event.target) return; // return if clicked element is not an anchor (isAnchor function should be also implemented by you. For example, you can add some class on every anchor and check if clicked element is <a> tag with this class)
if (window.location.href !== window.location.origin) { // check if you are currently on the homepage
event.preventDefault(); // if not on homepage then prevent default <a> tag redirect
window.location.replace(event.target.href); // and replace current history item URL with the new URL
}
}

How to change URL path when paging using ajax + jQuery

I am using ajax post requests for doing paging on a feed in my site. When getting the post request data I am reforming the page by clearing previous data and rendering the new data that came from the request. I want to be able to change the URL as well so saving the new page link will get the user to the current page.
Example:
User on page example.com/feed - seeing content of page #1
User clicking to get to page #2 -> ajax post is send and data on the page is changed using js (no refresh)
URL is still example.com/feed but the content is of example.com/feed?page=2
How can I set the URL to point to the new page without triggering a refresh (no redirect) ?
I am using Nodejs + express.
I understand you are aiming at a single page application.
While keeping the url is nice, note you might want distinct urls for directly accessing different parts of your application. Still, you can load content with AJAX and keep a smooth application. The way to go is using the hash part of the location.
The Sammy.js framework gives you a nice base to build upon, you can try it out.
You can use history pushstate but some browsers does not support.
history.pushState({id: 'SOME ID'}, '', 'myurl.html');
And don't forget about window.onpopstate, it pops if user clicks back button.
Redirect the user to an anchor point.
Page 2
And in your document.ready:
if (window.location.hash.length > 1){
var pageNumber = window.location.hash.substring(1);
loadPage(parseInt(pageNumber));
} else{
loadPage(0);
}
I don't believe it is possible to change the query part of the URL without triggering a refresh (probably due to security issues). However you may change the anchor and use an event listener to detect when the anchor is being changed.
//Listener
$(window).on('hashchange', function() {
if(loaction.hash.length > 1) {
//The anchor has been changed.
loadPageWithAjax("example.com/feed.php?page=" + location.hash.substring(1));
} else {
//Load standard page
...
}
});
Change the anchor to load new feed
Page 2
Remember to not use an anchor that is used as an id, since this makes the browser scroll to that element.

Trouble forcing browser to treat button click as history traversal event

I am building a website that is navigated through a series of directional buttons. Right and left clicks move between different images associated with one project. Up and down clicks move between projects.
What I am trying to do is ensure that when a user clicks up or down (i.e. between projects) that this is registered as a history traversal event and that a new entry for the new project is visible within the browser's history.
The code that I have sets an event on the the click of the navigation buttons that makes the necessary changes to the pages content, and then I attempt to push the new page to the history object by calling this function (see here and here for background information):
var pushToHistory = function(url, pageTitle, html) {
history.pushState({'html':html, 'pageTitle':pageTitle}, '', url);
}
I supply the arguments to this function elsewhere by doing the following after the page has loaded the new content:
html = document.getElementsByClassName('main-frame')[0].innerHTML
pageTitle = 'http://mysite/'+newpath; // new path specifieds the new item.
this.pushToHistory( url, pageTitle, html);
Now the problem I am having is that the result of all of this is that both in Chrome and in Firefox the history is updated in a way that is mostly correct: the url in the history's state object is correct, as is this the content. So that if I click on one of these history events, the correct page is retrieved.
However, the page title, which is shown in the list of history items is incorrect. It is always the title of the page that was loaded when the site was intially loaded. So if I load mysite/a-project, and the title of the page is "My Site - A Project" that is always what appears in the box. I have also checked my code to ensure that the pageTitle object is correct, so dumping pageTitle before calling history.pushState() shows the correct title.
Any ideas?
I discovered the problem. I needed to set document.title first. That meant somewhere before I call history.pushState(), I needed to do this:
document.title = theNewTitle;

is it possible to change change the url in address bar or browser on certain event

you all have used pinterest, you can see that when you click on any pin, a div is added and lightbox is shown on the same page but the url is changed to that of actual pin page. i have the same lightbox to show data, is it possible to change the url like that?..
one thing i want to tell is that, i have link which has onclick event which calls view() method, in which i am calling another page with ajax request, which shows the content of that page on my page, i want to change url when this link is clicked and back to previous url when closed..here is my code
function view(){
$.get('mypage.jsp', function(html) {
$(html).hide().appendTo('body').fadeIn(500);
}, 'html');
};
This feature is known as HTML5 Push State. Here's a related StackOverflow question which may provide more insight. Good tutorial for using HTML5 History API (Pushstate?)
I haven't checked Pintrest's solution. But is hash what you're looking for?
window.location.hash="Whatever-you-want-to-add-to-the-URL"
This will change http://stackoverflow.com/posts/11968693/ to http://stackoverflow.com/posts/11968693/#Whatever-you-want-to-add-to-the-URL
Yes, with HTML5's new history API. Where the lightbox is triggered, add something like this:
var hist = window.history;
hist.pushState({ image: [IMAGE URL] }, 'lightbox', [URL]);
This will change the current URL without reloading the page, and will create an entry in the browser history, so users can use their browser back button to return to the previous state (in this case, before they opened the lightbox).
You can change the url (not only the hash) by using the pushState or replaceState functions on the history object. More details: http://diveintohtml5.info/history.html

passing different variables to same page

I am trying to build a web app mainly using html and javascript. I use a number of different variables in the app that are passed through the url.
here are the problems, I have some links that link to the page the app is currently on, just with changed variables, but while clicking on the links does change the url value, the page does not change/reload for the new values when using and an href, is there a clean way to force the page to reload if you link to the current page, or change the url?
currently I am using jQuery to set the window.location with the new variables then reloading the page.
also, I have a similar problem for using the back button on the browser. It will change the url but not refresh the page, so if you have a variable set to 1 you change it to be 2, that works and the page will reload with the variable set o 2, but if you go back using the browser history the url will say that your variable should be 1, but the rest of the page will still act like the variable is 2, until you refresh the page.
is there someway to set a page so that the it will automatically refresh when you go to the page from the same page, either through links or going forward or backward with the browser history?
as per request here is part of the parts of the code I am having problems with:
first is the code for the creating the html elements onload
var sel_tags=document.getElementsByName("selected_tags")[0];
var temp="";
if(Tags==null)
{
temp="\<p>All Notes\<\/p>";
}
else//Tags not empty, and there are tag filters
{
var click= new Array("",a+ AtTagShow);
var GoTo="PageViewNotes.html?"
for (var i=0; i < Tags.length; i++) {
//if we are showing #tags, or a tag is not an #tag
if(AtTagShow||Tags[i][0]!="#")
{
click[0]=t+Tags[i];
if (temp.length>0)
{temp+="\<span class=\"spacer\">\/<\/span>"};
temp+="\<a class=\"selected_tags_label\""+
"href=\""+GoTo+click.join("&")+"\">\<span>"
+Tags[i]+"\<\/span>\<\/a>"
}
};
};
sel_tags.innerHTML=temp;
here is the jquery code for setting the onclick:
$(".selected_tags_label").live("click",function(){
window.location=(this.href);
window.location.reload();
});
an example url for this issue would be:
page.html?Tags=#rediculous,#meeting&AtTagShow=true
by clicking on the rediculous element the url would change to:
page.html?Tags=#rediculous&AtTagShow=true
window.location.href="page.html?Tags=#rediculous&AtTagShow=true"
Take a look at the jQuery History plug-in for setting your site up to have back / forward history. It helps with setting up states on your page, that call data based on what query parameters are in the URL string.
In modern browsers (IE8+, Opera 10.6+, Fx 3.6+, Safari 5+) you have hashchange event.
Instead of reloading page, maybe you can achieve desired results with something like this:
<script>
document.onhashchange = function(){
// do something
}
</script>
MDN might be also helpful.
If you are using query parameters (things after the ? mark in the URL), then changing a query parameter and setting window.location to that new URL should cause a new page load from the server.
If you are using hash values (things after the # mark int he URL), then changing the hash value will not cause a new page load.
So, if you want a fresh page load from server each time you change a value, then you should be using query parameters. Back and forward should also work fine when using query parameters.
If you're purposely trying to do all of this with hash values to avoid an actual server page reload, then you will have to do more coding to intercept hash changes and process them. That is easier to do in modern browsers than older browsers using the window.onhashchange event. See this page on MDN for more info.
Browser reloads the page, whenever any of these parts of the URL are updated via window.location:
Domain
Port
Path
Query string
But it won't load the current document, if you change the fragment_id part (which is simply a reference to an HTML element inside the current document).
Thus from what you say, I guess you're updating the fragment id.
Also this might help to know that window.location.reload() method does the work of F5 key.

Categories

Resources