How can I retrieve the full URL to which an anchor links using jQuery / JavaScript consistently across all browsers? For example, I want to return http://www.mysite.com/mypage.aspx from .
I have tried the following:
$(this).attr('href'): The problem is that jQuery returns the exact value of the href (i.e., ../mypage.aspx).
this.getAttribute('href'): This works in Internet Explorer, but in FireFox it behaves the same as above.
What is the alternative? I cannot simply append the current site's path to the href value because that would not work in the above case in which the value of the href escapes the current directory.
You can create an img element and then set the src attribute to the retrieved href value. Then when you retrieve the src attribute it will be fully qualified. Here is an example function that I have used from http://james.padolsey.com/javascript/getting-a-fully-qualified-url/:
function qualifyURL(url){
var img = document.createElement('img');
img.src = url; // set string url
url = img.src; // get qualified url
img.src = null; // no server request
return url;
}
Related
I know that my code works because I have been using it in firefox. When I switched to chrome, this code snippet has stopped working due to chrome unable to read the url generated by URL.createObjectURL().
export const image_preview = () => {
$('.js-thumbnail').off()
$('.js-thumbnail').on('change', function(event) {
// add event to each file input
const img = $(this).siblings('img')
const url = URL.createObjectURL(event.target.files[0]) // url to user's image
img.attr('src', url)
URL.revokeObjectURL(url) // free the allocated object
})
}
The url itself is generated but chromium fails to load it in my image tag.
Some posts suggests to use webkitURL api instead of URL but that didn't work either. Do you know the cause? Is this also a problem in other browsers as well?
You need to wait for the image has loaded before revoking its URL.
Image resources begin to load in a microtask after we set their src (among other reasons to allow setting crossOrigin properties after we set the src), so when the browser will read the src change, the line URL.revokeObjectURL(url) will already have been called, and the blob:// URL already pointing to nowhere.
So simply do
const img = $(this).siblings('img')
const url = URL.createObjectURL(event.target.files[0]) // url to user's image
img.attr('src', url)
img.one('load', (e) => { URL.revokeObjectURL(url); });
I have json feed that gives me thumbimage url.
This returns url like /webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png
Now, before /webapps/ It needs "app.toronto.ca" to get the full path. So I've replaced "localhost" into "app.toronto.ca" like so. And it gives me full path to image.
Now, the trouble is that, even though I retrieve full URL, image.src syntax will still force computer to add 'Localhost:5000/' to my perfectly assembled URL.
function displayEvent(array,i){
var image_url = array[i].calEvent.thumbImage.url;
var image =new Image();
var hostname = location.hostname;
toronto_host = hostname.replace("localhost","app.toronto.ca") +
image_url;
alert(toronto_host); //this give me pull URL path//
image.src = toronto_host;
alert(image.src);
// this gives localhost:5000/what_i_had_in_toronto_host//
document.getElementById("party_picture").appendChild(image);
};
since no image path starts with http://localhost:5000/... i can't use any image while i'm testing the site.
Any way i could assign image src with the correct url without localhost part?
thank you!
Image src attribute will always append the localhost ( or where the page originates from ), if you don't provide a complete URL ( in your case you provide everything except the protocol ).
toronto_host = hostname.replace("localhost","//app.toronto.ca") +
image_url;
// ^ appending '//' before your
// location will force the browser
// to set the protocol to the current
// one of the page.
This will make your img.src to behave as expected.
I have a relative, absolute and full qualified URLs that I want to turn into fully qualified URLs. I can do this by abusing the img tag like this
[
"someFolder/someFile.foo", // relative
"/someRootFolder/someFile.foo", // absolute
"https://somedomain.com/someFolder/someFile.foo", // FQ
].forEach(path => {
var img = new Image();
img.src = path;
console.log(img.src); // returns FQ for all URLs;
});
If you run it the result is
https://stacksnippets.net/someFolder/someFile.foo
https://stacksnippets.net/someRootFolder/someFile.foo
https://somedomain.com/someFolder/someFile.foo
It's seems wrong to abuse Image to do this. First it's an image tag and my URLs have nothing to do with images and second I don't want to trigger a network request.
URL doesn't work as it will fail on both first 2 URLs
Uncaught TypeError: Failed to construct 'URL': Invalid URL
I thought maybe window.location would have a function getURL or something you could pass a path to and it would require whatever it's doing for image.src but I don't see anything on MDN.
Is the another way that's just as simple (1/2 lines) but doesn't use the image tag and doesn't cause a network request?
This is usually done with an <a> tag.
[
"someFolder/someFile.foo", // relative
"/someRootFolder/someFile.foo", // absolute
"http://somedomain.com/someFolder/someFile.foo", // FQ
].forEach(path => {
let a = document.createElement('a');
a.href = path;
console.log(a.href); // returns FQ for all URLs;
});
Which also has other advantages over an <img> in that it contains some window.location like properties :
like hash, pathname, path, origin, and maybe others I forgot.
[
"someFolder/someFile.foo#hi", // relative
"/someRootFolder/someFile.foo#hi", // absolute
"http://somedomain.com/someFolder/someFile.foo#hi", // FQ
].forEach(path => {
let a = document.createElement('a');
a.href = path;
console.log(a.pathname, a.origin, a.host, a.hash); // and maybe some others
});
I'm trying to dynamically generate an anchor for a given content (documents and/or images stored on Cloudinary.io, in this case), but the documents I'm storing have a hash value rather than a filename (i.e.: c9eed62bd1534c382a3b89241b24b1ddd17b3793 instead of sample.pdf).
Here's the function I'm using to generate the anchor:
function download(url, download) {
if (url) {
var a = document.createElement('a');
if (a) {
a.href = url;
a.download = download || '';
a.target = '_blank';
a.click();
}
}
}
The problem I have is, when I execute the function, the browser downloads the file for me, but with the name in the href attribute rather than the download attribute.
This is the event I use to fire the download:
$('.link').on('click', function (e) {
download($(this).data('url'), $(this).data('name'));
});
And this is a sample HTML element containing the data to trigger the event:
<span class="link" data-url="http://res.cloudinary.com/dxsky7h00/raw/upload/v1483364241/627ec3e4afa08749ac4aff8d2917a38f586a5790" data-name="fs545554545454.xls"><i class="icon-file-o"></i>fs545554545454</span>
Maybe I understood the download attribute for the <a> element in a wrong way, but I thought, when specified, it forces the browser to download the resource rather than trying to open it on one hand and, on the other hand, if download="something" is used, the resource will be downloaded with the name being 'something' rather than what's in the href attribute.
What am I missing for this sample function to work?
EDIT I'm currently testing this on Chrome 55.0.2883.87 (64-bit), but as this entry on caniuse.com states, it's compatible
#tsh asked the right question. The problem lies in the fact the href attribute references an external resource, hence we're dealing with a cross-origin reference and the browser won't let me download it with another name.
I tested it with a local file and it worked, so the problem lies within my implementation. Thanks to all anyway :)
I'm crawling a website using CasperJS and I have an interesting problem.
In Caspers's evaluate function, I want to extract src attribute from image <img> element. Here is code that will be executed in my evaluate function:
function crawl(){
var product = {};
try{
product.title = jQuery('#title').html();//Get title
product.price = document.getElementsByClassName("price")[0].innerHTML;//Get price
var imageSrc = jQuery("#next").attr("src")
product.image =imageSrc;
}
catch(e){
}
return JSON.stringify(product);
}
Here is how evaluate function is handled in Casper:
casper.then(function(){
scrappedProductInfo = this.evaluate(crawl);//Get info
console.log("Page crawled");
utils.dump(scrappedProductInfo);
});
When I execute my CasperJS script, from evalute() function in image attribute of returned object instead of image link I get base64 representation of the image:
\ndata:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABQODxIPDRQSEBIXFRQYHjIhHhwcHj0sLiQySUBMS0dARkVQWnNiUFVtVkVGZIhlbXd7gYKBTmCNl4x9lnN+gXz/2wBDARUXFx4aHjshITt8U0ZTfHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHz/wAARCAEKAKkDASIAAhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAIFAQQGAwf/xAA+EAACAgEBBAUICAQHAQAAAAABAgADEQQFEhMhFDFBVHEGM1FSkZOxwRUiMmGBkqHRI0Jy8CQ1RGKi4fFz/8QAFwEBAQEBAAAAAAAAAAAAAAAAAAECA//EACARAQEBAQACAgIDAAAAAAAAAAABEQIS.....
When I open the same page in Chrome and when I execute crawl function in Chrome console, I get src as link and not as base64 string. When I right-click on element and inspect it, i can clearly see URL and not base64 encoded string.
Any suggestions?