How to remove part of the URL within window.location? - javascript

I have fetched window.location into a variable. Now, I want to remove part of the string from the href within the location object, but still retain the object.
In other words, I want to modify the location object, and still be able to use window.location.protocol and window.location.host, but those functions need to work on the modified object.
For example, something like this where my browser displays "https://my.domain.org/site":
var thisloc = window.location;
Modify the href within that object to "http://my.domain.org/othersite"
//now I want it to fetch "http" instead of "https" based on my modified object
var thisprot = thisloc.protocol;
Will that work? If it does, it would be very nice. Otherwise, I have to parse the URL to get the protocol, host and pathname from a modified href, which would also accomplish the same goal.

Inspired by James Padosley's post on Parsing URLs with the DOM!, the trick here is to use an anchor element (<a>) as a URL builder/parser. With any anchor element, if you set its href property to some URL, it will be parsed by the DOM. Thereafter, you can freely modify the parts of that URL via properties on the anchor element. Query the href property at any time to see the full URL.
Using the example from the question…
var builder = document.createElement("a");
builder.href = "https://my.domain.org/site";
builder.protocol = "http://";
builder.pathname = "/othersite";
console.log(builder.href); // http://my.domain.org/othersite
At this point the anchor element's href will now be http://my.domain.org/othersite, as requested. Here's a JS Bin demonstrating it in action: http://jsbin.com/omoqen/1/edit.
The beauty is that anchor elements have the same URL component properties as the window.location object:
protocol
host
hostname
port
pathname
search
hash

These are browser properties - you can fetch and modify the values, but referring to the property won't work in the way you describe.

Related

Current Page URL in a hyperlink

In the code below, I am hard coding the url.
<a class="button_link" href="https://somewebsite.com/submit/?url=http%3A%2F%2Fsomecrazyurl.com" target="_blank" aria-label="Sharei">
Instead I want something like this:
<a class="button_link" href="https://somewebsite.com/submit/?url=returnpageurl()" target="_blank" aria-label="Sharei">
Edit: For the record I used
$(location).attr('href');
However nothing gets returned.
Is there any cross-browser Javascript to return the current url of the page?
If you are looking for a browser compatibility solution use
window.location.href
where document.URL is having issues with Firefox with reference to this
<a class="button__link" href="#" target="_blank" aria-label="Sharei" id="current_url">Current URL</a>
This is simple to use as below with no complexity ,the thing what I found is you are not assigning any value to the href attribute and by default in jquery it assigns back
https://somewebsite.com/submit/?url=returnpageurl()
Now the below one should work for your case,
$("#current_url").attr("href",window.location.href );
To get the path, you can use:
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
You can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if you're interested in rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinks = $('a[href^="http://google.com"]');
This is easy to achieve by using the window.location.href JavaScript window property.
Html Example:
my link
Javascript
var a = document.getElementById('link1');
a.href = a.href + '?returnUrl=' + encodeURIComponent(window.location.href);
With jQuery:
$('#link1').attr('href', $('#link1').attr('href') + '?returnUrl=' + encodeURIComponent(window.location.href));
Note the use of the built in function encodeURIComponent(str) reference.
The encodeURIComponent() function encodes a Uniform Resource
Identifier (URI) component by replacing each instance of certain
characters by one, two, three, or four escape sequences representing
the UTF-8 encoding of the character (will only be four escape
sequences for characters composed of two "surrogate" characters).

href attribute set, javascript sees as empty string

I am experiencing odd behaviour in Chrome (v43.0.2357.134) whereby I am reading an anchor element's .href attribute, but in specific circumstances its value is an empty string.
I would like the .href value to be populated on all anchors.
Issue
Specifically, this is what is being observed:
//Bad (unwanted) behaviour
var currentElem = ; //Code to pick out an anchor element
console.info(currentElem.href); //"" (empty string)
console.info(currentElem.getAttribute('href'); //"path/to/other/page.html"
Edited to add/clarify: Note that in this screenshot, at the point of reaching the fourth line of code the value of nextPageUri is an empty string (otherwise would not have reached the debugger; line). The fifth line then populates nextPageUri with the .getAttribute('href') value, hence the value showing next to line two.
This is what is (correctly) seen within Firefox, and on the first TWO DOMs via Chrome:
//Good (desired) behaviour
var currentElem = ; //Code to pick out an anchor element
console.info(currentElem.href); //"http://example.org/root/dir/path/to/other/page.html"
console.info(currentElem.getAttribute('href'); //"path/to/other/page.html"
Background
Context: This is within a script to inline multiple pages of search results to a single page, and the anchor elements are located within a DOM retrieved via xmlHttpRequest. The code runs perfectly via Firefox for >100 pages.
Confusingly, the incorrect behaviour described above only occurs on the third and subsequent requests in the Chrome browser.
This is an issue with Chromium/Blink-based browsers: if you use DOMParser to parse string into a document, href properties with relative URI (i.e. doesn't start with http[s]) will be parsed as empty string.
To quote tkent from Chromium issue 291791:
That's because a document created by DOMParser doesn't have baseURI. Without baseURI, relative URI references are assumed as invalid.
Same thing happens if you use createHTMLDocument. (Chromium issue 568886)
Also, based on this test code posted by scarfacedeb on Github, src properties also exhibit the same behavior with relative URIs.
As you have pointed out, using getAttribute() instead of the dot notation works fine.
Chrome's "element.href" doesn't act any differently on the 3rd try than it does on the first 2 -- you mentioned that you are paginating, when this error happens. how does the "href" attribute on the Next Page link get set each time you arrive at the page? It seems likely that your code to evaluate the element's href attribute is simply running before the href is set -- as evidenced by your debugger being able to evaluate it after a pause.
Try and reproduce this issue in a plunkr.
I know you're checking if nextPageUri is empty.
But, could you try always using
nextPageUri = currentElem.getAttribute('href');
and see if that works?
I experienced a similar problem using a DOMParser for translating text/html pages coming from ajax requests and, after that, finding href's of <a> elements inside it.
For instructions purpose, this is how I'm using the parser
var parser = new DOMParser();
$.ajax({....}).done(function(request){
var page = parser.parseFromString(request, 'text/html');
});
Test yourself
If you want to test the behaviour of .href and .getAttribute("href") yourself, please run this code at chrome dev tools console:
parser = new DOMParser(); // create your DOMParser
// the next line creates a "document" element with an <a> tag inside it
parsed_page = parser.parseFromString('click here', 'text/html');
link = parsed_page.getElementsByTagName('a')[0]; // locate your <a> tag
link.href; // this line returns ""
link.getAttribute('href'); // this line returns "test"

Get path including GET variables using javascript

I need to get the whole path of page (excluding the domain) so I can show it in an iframe.
I currently use location.pathname to get the path, but the problem is that they may appear GET variables in the URL.
So for a page like article.php?id=23 I get only article.php using location.pathname, thus the page displayed in the iframe is simply a 404 page.
Is there any function to get the path including GET variables?
There probably isn't an out of the box function, no.
But you can use this as a reference to create your own:
Mozilla DOM Reference
Specifically, using window.location.pathname (strip the leading "/" if you don't want it) and window.location.search to get the querystring.
i.e
function whatIWant()
{
return window.location.pathname.substring(1) + window.location.search;
}
window.location.search.replace( "?", "" );
this will return the get variables.
LINK=http://www.javascriptkit.com/jsref/location.shtml
Answer to your question->no,there is no any built in function ,we have to make our custom function and parse it.
Get escaped URL parameter

How to get the parts of a url using document.referrer?

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:
window.location.protocol
window.location.host
window.location.pathname
but I can't figure out how to do it with document.referrer. Anyone got any ideas?
You can create an a element with the referrer as its url.
a elements (with hrefs) can act like location objects
var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';
There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:
var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');
If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

Why does URL Hash is added instead of being replaced?

When using a url like this:
http://localhost/nafham/?selection/12/24/122
The hashing is done in that manner:
http://localhost/nafham/?selection/12/24/122#?selection/12/24/122/الصف-الثالث-الثانوي/السنة-كاملة/الاقتصاد/self
However when any other part added to the URL, example:
http://localhost/nafham/?selection/12/24/122/test
The hash is added again on each action
http://localhost/nafham/?selection/12/24/122/test#?selection/12/24/122/الصف-الثالث-الثانوي/السنة-كاملة/الاقتصاد/self
http://localhost/nafham/?selection/12/24/122//test#?selection/12/24/122/test#?selection/12/24/93/الصف-الثالث-الثانوي/السنة-كاملة/الاقتصاد/self
Any idea why the Hash is added to the URL instead of replacing the current hash value?
Because you are using the part of the URL when you set the hash.
Use location.hash = "...". It should work.

Categories