I'm trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.
On this page, a JavaScript object is loaded from the page's URL:
http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]
and on this page, I'm trying to create a link to the same page that is shown above, but the URL contains characters that are not allowed in hyperlinks:
http://jsfiddle.net/M6dRb/
This link doesn't work because the URL contains characters that are not allowed in HTML links.
Is it possible to embed JavaScript objects into URLs without using characters that are not compatible with hyperlinks?
You can put a JSON string in an URL by URL-encoding it before putting it in the URL:
encodeURIComponent(JSON.stringify(object))
In your example, that would be:
http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D
As you might guess, the opposite of encodeURIComponent is decodeURIComponent.
You need to encode and decode with JSON
var link = document.getElementsByTagName('a')[0];
link.addEventListener('click', function(){
// this could also be done with location.hash = JSON.stringify(...);
var param = JSON.stringify(['your', 'array']),
href = '#'+this.getAttribute('href');
href += param;
location.href = href;
}, false);
// make string an object/array again
var obj = JSON.parse(window.location.hash.substr(1));
Related
I've got a CSJ variable to capture the last parameter of the URL. Given I'm interested on capturing the location and its position may vary (see example below), I managed to create a custom variable that will always give me the last parameter in the URL.
URL examples:
https://www.example.co.nz/location/**holmwood**
https://www.example.co.nz/find-a-location/auckland/**central-auckland**
The issue I'm having is that my script (see below) is not only capturing the last parameter of the URL, but any string after the "?" symbol, which are mainly UTMs.
Code:
function(){
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
So, on my GA view instead of seeing the ph + the location, I see a large string:
I know I could use page path and remove query from there, but for a specific event I'd rather sort that out from the custom variable because of the type of value I'm passing.
What else should I add to my script to keep it completely the same and exclude any query parameters that might be automatically tagged?
Thanks.
Rather than returning the first split, I would then put it through an additional one where you are splitting on the '?'
function(){
var pageUrl = window.location.href;
var lastSlash = pageUrl.split("/")[pageUrl.split("/").length - 1];
return lastSlash.split("?",1);
}
I am trying to append a query string on a URL to all anchor links on page. If the page URL was www.example.com/page?paramter1=variable¶meter2=variable2
The variables may change each time and it is to be used for analytics.
I would like all the other links on the page to automatically get ?paramter1=variable¶meter2=variable2 added to them when the page loads.
I had been playing around with the following script but i can't seem get variable 'myquerystringtoadd' to be populated by the query string in the URL which I don't necessarily know what the parameters would be so it is the whole query string.
var querystring = 'myquerystringtoadd';
$('a').each(function()
{
var href = $(this).attr('href');
href += (href.match(/\?/) ? '&' : '?') + querystring;
$(this).attr('href', href);
});
Any help would be much appreciated!
How about using querySelectorAll in vanilla javascript instead of jquery. Also, kill your leading '?' in querystring. And if part of your question involves how to get the querystring from the current page's url, use window.location.search.
In the snippet below, you have some google search anchors. One searches 'x', and the other searches 'y'. Your query string further specifies that in both anchors, you want a safe search for images.
// You will use window.location.search
let querystring = '?tbm=isch&safe=active'
if(querystring.startsWith('?'))
querystring = querystring.replace('?', '');
for(let a of document.querySelectorAll('a')) {
a.href +=
(a.href.match(/\?/) ? '&' : '?') +
querystring;
}
<a href='https://www.google.com/search?q=x'>search x images safely</a><br/>
<a href='https://www.google.com/search?q=y'>search y images safely</a>
Note: You may have noticed that I'm editing this question a lot, but it's just to to work with google query strings.
I 'd like to grab the current URL, replace a part of the pathname within it, and open the result in a new tab.
The current URL looks something like this:
http://website.com/file.php?identificator=11111&folder=name
I would like to get the URL (I assume using "window.location" to be most suitable (?)), then replace the parameter "name" (variable, could be different at any time) with "name2" (fixed value) and open resultant URL in a new tab, possibly multiple times.
I've tried looking into replace(), but couldn't get into isolating the parameter inside the pathname.
How would one proceed? jQuery could be a possible replacement too.
Thanks for any help.
<script>
url = window.location.href;
newurl = url.replace(url,"http://website.com/file.php?identificator=11111&folder=anything
"); // your replacement
window.onload = window.open(newurl);
</script>
*untested code
I want to remove the string code=hads1328fas& on my URL, so that
BEFORE
http://example.com/main/index.php?code=hads1328fas&store=food#home
AFTER
http://example.com/main/index.php?store=food#home
However, the string code=hads1328fas& may not always the same, so the code below won't works in this case.
var url = window.location.href;
url.replace('code=hads1328fas&')
Is there any way that is possible for the case?
Thanks
Use regular expressions:
url = "http://example.com/main/index.php?code=hads1328fas&store=food#home";
url = url.replace(/code=[^&]+&/,'');
After this, url will contain
http://example.com/main/index.php?store=food#home
I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.