Programmatically send use to different endpoint - javascript

Say the user is on http://example.com/dashboard, How would I programmatically change the endpoint without affecting the root url, ie. on an event the user would be sent to http://example.com/section.
My issue is is that the URL root can sometimes change depending on the client or the server. So I can't hard code it in.
http://sub.example.com/dashboard
http://dev-example.com/dashboard
http://production-example.com/dashboard
How do I get the root of the URL and swap in my new endpoint and then redirect the user?

use window.location .You can build your url with help of window location api object
function redirect(endpoint){
var paths = window.location;
var url = `${paths.origin}/${endpoint}`
return url
//for page redirect use window.location.href = url
}
console.log(redirect('one'))
console.log(redirect('two'))

You can use location.assign() to load another URL:
$('#elem').on('click', () => location.assign('/some/path'));
This will redirect you to /some/path on $('#elem') click (assuming you use jQuery, but that doesn't matter really)

Get the root URL using window.location.origin
Concat that string with whatever endpoint you want to add
Assign that to window.location.href inside your click event listener
callback function
So the code will look something like this:
const BASE_URL = window.location.origin
document.querySelector('#yourButtonId').addEventListener('click', (e) => {
e.preventDefault();
window.location.href = BASE_URL + '/your_end_point';
}
Refer: Window.location addEventListener

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

Retrieve URL of AppScript using Javascript

I am trying to reload the current page with a new parameter, but I am unable to retrieve the correct URL of the webpage. I am getting an alternate URL instead of the one that triggers the web app
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=menu&id=1
when the button is clicked I want the action parameter's value to change and the page to reload as
https://script.google.com/a/user/macros/s/A...ljhGC/dev?action=checkout&id=1
Here is my javascript within the HTML File
console.log(document.url);
var url = new URL(window.location.href);
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.set('action', 'checkout');
url.search = search_params.toString();
var new_url = url.toString();
window.location.replace(new_url);
console.log(new_url);
}
This is the URL that gets logged
https://n-ikwx...khq-1lu-script.googleusercontent.com/userCodeAppPanel?action=checkout
How do I retrieve the actual URL that is in the address bar?
Thanks in advance!
Issue:
A iframe with different origin cannot read the href property of location of the the parent/top frame, which is write only. So, You can't.
Solution:
You can however pass the url from server side.
Server side:
function getTopUrl(){
return ScriptApp.getService().getUrl();
}
Client side:
var topUrl;
function getTop(){
google.script.run.withSuccessHandler((url)=>{topUrl=url;}).getTopUrl();
}
window.addEventListener('load', getTop);
References:
Where is my iframe in the published web application/sidebar?
Same origin policy
Service#getUrl
google.script#run

How to detect parameters globally and keep the state after navigation

I need to find the way to keep the parameters in the url upon navigation if they are entered once, ie: ?aff=john
So for example, user comes to website.com/?aff=john and navigates to about-us I need to make that url parameters are kept, so the full website name is: website.com/about-us/?aff=john
This is what I've tried so far, but it is not working.. it keeps adding the url parameters (window.location.search)
var params = false
var baseUrl = ''
var currUrl = window.location.href
if (window.location.search != '') {
params = true
}
if (params) {
baseUrl = currUrl + window.location.search
window.location.href = baseUrl
}
Thanks.
EDIT: already tried proposed.. not working.
You can use sessionStorage to save navigation data into a key. Pick it up whenever required. Now-a-days, all browsers support it except Opera mini.
Hopefully, your software does not have browser constraints and your application does not have to work on outdated browsers.
As copied from mozilla site, code to use sessionstorage would be like :
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove a key from sessionStorage
sessionStorage.removeItem('key');
// Remove all data from sessionStorage
sessionStorage.clear();
This way, you won't need to append it on every page. For the domain url and in current browser session, you can get it from sessionStorage.
You can save the query string using window.location.search and then you can add link handler in using jQuery like below:
var glString = window.location.search;
$('a').on('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
or if you prefer javascript
var glString = window.location.search;
var links = document.getElementByTagName('a');
links.addEventListener('click', function(evt) {
evt.preventDefault();
window.location = $(this).attr('href') + glString;
});
You can temporary save the previous url using sessionStorage.
sessionStorage.setItem('parameter', 'dataString');
sessionStorage.getItem("parameter");

JQuery / Ajax - update URL without refreshing the webpage - should be compatible with IE8 and IE9

When I first load my webpage, it loads to this URL:
/default/
Now, when I click the "nextPost" button on the screen (which has an attribute called data-nextPostNumber), this is the code which I have:
event.preventDefault();
var nextPost = $(this).attr('data-nextPostNumber');
$("body").load("/default/?postNumber=" + nextPost);
So this loads the URL (assuming that nextPost=2)
/default/?postNumber=2
However, this was loaded using ajax so the actual URL in the URL bar is still
/default/
What I want to do is get the GET variables in the URL which was loaded through ajax. I have this code (which gets the GET variables in the URL and puts them in a dictionary called params):
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
But this code just gets the GET variables in the URL which is in the URL bar - not the URL which was loaded using Ajax. So, is there a way for me to take the URL which was loaded using Ajax and place that URL in the URL bar? If not, is there any way for me to solve my issue? Please note that I need it to be compatible with IE8 and IE9.
You can use the new History API method pushState:
<input type="button" value="Post #2"
onclick="history.pushState(null, 'MyWebsite Post #2', 'http://mywebsite.com/?postNumber=2');" />
When you click this button, the location will change to http://mywebsite.com/?postNumber=2 and then you can call your getQueryParams function as follows:
getQueryParams(location.search);
The pushState will NOT work if you open the page as a file, in another words, it must come from a webserver (it works with localhost)

How do we update URL or query strings using javascript/jQuery without reloading the page?

Is there a way to update the URL programatically without reloading the page?
EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
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
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
Prefix URL changes with a hashtag to avoid a redirect.
This redirects
location.href += '&test='true';
This doesn't redirect
location.href += '#&test='true';
Plain javascript: document.location = 'http://www.google.com';
This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
Yes - document.location.hash for queries

Categories

Resources