Friday, September 1, 2017

To update URL or query strings using javascript/jQuery without reloading the page

Syntax
 replaceUrl(window.location.href, "BookName", "DotNet");


function replaceUrl(uri, key, value) {
            debugger;
            var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
            var separator = uri.indexOf('?') !== -1 ? "&" : "?";
            if (uri.match(re)) {
                window.history.replaceState("", "Title Name", uri.replace(re, '$1' + key + "=" + value + '$2'));
            }
            else {
                window.history.replaceState("", "Title Name", uri + separator + key + "=" + value);
            }
        }

window.history.replaceState

var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
    var title_ = document.getElementsByTagName('title')[0];
    if(title_ != undefined){
        title_.innerHTML = title;
    }else{
        var title__ = document.createElement('title');
        title__.innerHTML = title;
        var head_ = document.getElementsByTagName('head')[0];
        if(head_ != undefined){
            head_.appendChild(title__);
        }else{
            var head__ = document.createElement('head');
            document.documentElement.appendChild(head__);
            head__.appendChild(title__);
        }
    }
    replaceState_tmp(obj,title, url);
}


history.pushState(null, null, link.href);

The history.pushState() function takes three parameters:

    1.state can be any JSON data structure. It is passed back to the popstate event hander,

   2.title can be any string. This parameter is currently unused by major browsers. If you want to set the page title, you should store it in the state argument and set it manually in your popstate callback.

     3.url can be, well, any URL. This is the URL you want to appear in the browser’s location bar.


var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host            Returns the hostname and port of a URL
hostname        Returns the hostname of a URL
href            Returns the entire URL
pathname        Returns the path name of a URL
port            Returns the port number the server uses for a URL
protocol        Returns the protocol of a URL
search          Returns the query portion of a URL

No comments:

Change default Port on Next.js app

 If any other app or process is running on port 3000 , you will get this error in your terminal Port 3000 is already in use. error Command f...