Download a file when clicking an anchor in Internet Explorer - javascript

I've seen similar questions but so far am unable to solve this problem:
I am trying to download a file (mp4) located in Azure Blob storage when an anchor is clicked. This currently worked in Chrome, Firefox, Safari etc but from what I'm aware IE doesn't support the download attribute.
I have access to the storage account so tried changing the Content-Type to application/force-download and the Content-Disposition to attachment;filename=someName. This resolved the problem for Firefox cross domain limits but still no joy in IE. I have tried application/octet-stream but this did not work either.
Currently in IE11 it tries to open Windows Media Player (not sure why), but in IE10 and lower nothing happens, the browser just hangs whilst trying to navigate to the blob storage URL.
So next was to try some client side. Using Jquery I attempted the following:
$('.fallback[data-auto-download]').click(function () {
var $this = $(this);
window.location = $this.attr('href'); //download file
setTimeout(function () {
window.location.href = "/Content/Confirmation";
}, 3000); //redirect to new page after timeout
});
And this is how it looks in the markup:
<a class="fallback" data-auto-download href="http://someBlobURL">Download video</a>
As mentioned above this is not working for IE. Are there any current methods to get this to work? Research states to change the Content Type but that doesn't seem to get it working.
Please note: We cannot use right click to save target as because this project requires a new page to be loaded when the file download has been initiated.

Related

How open link in safari mobile app from webview

There are many topics of this here, but they all need native code interaction to work.
In my case, it is necessary to be able to do it directly from the url, without any interaction with my mobile app.
I tried:
Open Google in Safari
and
Open
and based in this post.
<script>
$(document).on('click', 'a[target="_blank"]', function (ev) {
var url;
ev.preventDefault();
url = $(this).attr('href');
window.open(url, '_system');
});
</script>
but nothing works.
Anyone have any idea how to fix this?
There is a trick. We know iOS Safari have these available URL Schemes:
(HTTP) — http://websiteurl
(HTTPS) — https://websiteurl
x-web-search://
(FTP) — ftp://locationtofileonftpserver
If you use Click here or window.open("http://somewebsite"). It always use current browser to open url.
x-web-search://?[keyword] - It will switch into Safari app but search for the keyword
Luckily we still have ftp:// left. It will switch to Safari app. But first you need to setup a public folder in your hosting & create a bridge html file to redirect user back to http:
ftp://{youripaddress}/bridge.html
window.open("https://yoururl", "_self");
Now you can open your website in the default Safari app from any browsers.
The original answer is here: JS - Mobile - Open Safari from any browser
Update (2021-01):
Apple seems to fix this on iOS, this is no longer work!
If this is running in safari it should comply with safari async call restrictions regarding popups as explained here.
You should fix your code so that the window open will be outside the function, Something like that:
<script>
var windowReference = window.open();
$(document).on('click', 'a[target="_blank"]', function (ev) {
var url;
ev.preventDefault();
url = $(this).attr('href');
windowReference.location = url;
});
</script>
There isn't a URL Scheme for Safari on iOS.
See Apple's Documentation:
https://developer.apple.com/library/archive/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html
Have a search around and you will see similar answers:
What is Mobile Safari's custom URL Scheme?

Issue with anchor href set to a "blob:" URL using a target of "_blank" in Chrome

I am developing a website which allows users to download a PDF version of a page. The current solution is to render the generated HTML to a PDF on the server, which returns the Base64-encoded PDF as a result. A Blob is created from this data, followed by an ObjectURL as follows: -
const blob = new Blob([B64A.decode(pdfdata)], {type: 'application/pdf'});
dataURL = (window.URL || window.webkitURL).createObjectURL(blob);
The dataURL (which is in the form "blob:http://www.example.com/abcd1234-abcd-abcd-abcd-abcd1234efa") is then assigned to the href attribute of an anchor tag. The target attribute is also set to "_blank" so that the generated PDF is opened in a new tab.
This worked absolutely fine up until around a week ago. In Firefox, everything still works, however in Chrome there is a problem. When clicking the link, a tab quickly opens and then immediately closes. Removing the target attribute causes everything to work properly, although the PDF is loaded into the current tab which is not what I want. Nothing is logged to the console, so I am not getting any clues from there.
Does anyone have any ideas as to why this is happening? As this has only just started happening I am assuming it's an issue with the latest version of Chrome (I am running 57.0.2987.98 (64-bit) on Linux, although a colleague also has the same issue with Chrome on Windows 10).
EDIT:
I just created a CodePen example to demonstrate this: https://codepen.io/anon/pen/OpOGbE
Click the button and two links should be generated. The first should open normally in the same page. The second should open in a new tab, but does not in Chrome (for me it displays the same behaviour as mentioned above).
While running this test I just noticed that in an incognito window the issue seems not to exist, and the new tab opens correctly...
It seem to be a temporary bug in Chrome. The code works with current Canary (beta) version of Chrome (v.59.0.3044.1) as of this writing.
As a temporary workaround you could try using the original Base-64 data and just prepend a data-uri header to it, then use this as source for href:
const dataURL = "data:application/pdf;base64," + pdfdata;

Bookmarklet to activate reader mode in Firefox on Android

Recently a change happened with Firefox on Android which stopped me from using the work around of adding something to my reading list and opening it from there to force a page into reader mode. With that in mind I tried to find and then finally make a bookmarklet to force a page into reader mode for me.
So far I have found that by adding 'about:reader?url=' to the beginning of a url will try to open any page into reader mode. From there not knowing much about javascript I tried to cludge together something using other examples I found on the web. To start I just figured out how to add to the url and was able to get that working
javascript: window.location = window.location + 'about:reader?url=';
The above will add onto the end just fine but when I move it to the beginning it no longer works so when I try
javascript: window.location = 'about:reader?url=' + window.location;
Nothing happens at all even on a page that will just allow reader mode. When I replace the stuff I am adding with just 'test' though it will happily cause the page to go to 'testhttp://www.google.com/' or wherever else. I have tried it on not only my android phone but also my desktop. What am I doing wrong as from what I can see this should work?
Almost certainly Firefox considers it to be a security risk to allow Javascript to change a page to any location beginning with about:.
Using the Javascript console in Firefox in Windows to run this code:
window.location = 'about:reader?url=' + window.location;
returns error:
Access to 'about:reader?url=...' from script denied
Here is a "work around" that might ease your particular pain:
javascript:(function(){prompt('Copy the below text and then paste it into the URL bar:', 'about:reader?url='+encodeURIComponent(document.location))})();
It will prompt you with a url you can copy and then paste into the URL bar.

How to use javascript to preload images

I have looked at a number of SO questions on how to preload images, I have created a function
$(images).each(function () {
var img = new Image();
img.src = this;
$(img).appendTo('body').css('display', 'none');
});
Which appends the images to the dom. However when I add a product to my cart, (the minicart will contain the images which have been preloaded), chrome still produces a request on that minicart image even though it has been preloaded (I can see the image in chrome developer tools). How do I get chrome to use the image which has already been loaded instead of getting another one from the server?
your server is sending wrong headers; do a search about Cache-Control, Expires, Etag and Pragma and set them to cache your images instead of download
chrome is buggy or it intentionally downloads the image twice. for example setting display:none too early may cause the problem, use position:absolute;left:-100000px; instead
your developer tools is set to disable cache (click on the gear icon, then uncheck General > Disable cache (while DevTools is open) )

How to cancel an image from loading

Suppose in Javascript that you assign the SRC to an IMG tag. It is a large SRC and you want to cancel it before it has finished loading. Assigning the SRC to another image will not stop the data from loading.
That is, in the middle of the load you can assign the SRC to another smaller image and the smaller image will be loaded and appear in your browser. However, the original SRC still continues downloading.
Similarly, deleting the IMG node will not prevent the SRC from continuing to download. No guesses please, look at the repro steps.
REPRO
Load this URL in Chrome in Windows: http://68.178.240.17/imgLoadTest/imgLoadTest.htm
Open up the developer panel by pressing CTRL-SHIFT-J
On the top row of icons in the Chrome developer panel click the Network icon to watch network activity.
On the web page loaded in Step 1 click the Load Image button and watch the developer panel as a large (32meg) image starts loading.
On the web page click the Try To Cancel button to load a different image.
A small image loads, but watch the network in the developer panel and notice that the large image continues to download.
Quick answer
Setting the src attribute of the img tag to the empty string will interrupt the current download, even on Chrome.
Details
Nowadays most of browsers implemented that out-of-standard mechanism thought in the old answer to programmatically abort the connection. This is not achieved through a protocol request, but with a client-side in-memory operation. Keep in mind that is not a standard behaviour, but most of vendors courtesy. That is, it could not work on every browser.
I've prepared a jsfiddle showing this mechanism in action (keep an eye at the network panel of the inspector).
Old answer (2011)
Your browser asks for that image with a specific HTTP GET request, as specified in HTTP protocol. Once it asks for it, the http server starts the transfer.
So, it is between the browser (as http client) and the http server.
Since http protocol does not takes into account the option to abort a transfer, the browser should implement a out-of-standard mechanism to programmatically abort the connection. But since this is not specified in any standard, i think you won't find any way to do that with javascript or any client side code.
Cancel with transparent base64 encoded GIF to avoid additional requests and double page load on android:
var img = new Image();
img.src = 'http://google.com/favicon.ico';
img.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI=;'
Although I can't find the bug report now, I believe this is a long-standing logged WebKit bug. Firefox (and IE I think) have more sane behavior. I'm going back a bit in my brain, but if I recall on those browsers, resetting the img.src will in fact cancel outstanding downloads. I am positive that Firefox does this when a download is "waiting in line" for a chance at an open HTTP connection, and I seem to recall that it will actually force close connections sometimes.
I've never found a way to coax WebKit based browsers into cancelling an img download in progress, whether it is just queued or already actively downloading.
This really sucks if you're making something like a mapping client and need more fine grained control over images.
Setting the .src property to an empty string should cancel the load:
//load image from url
var img = new Image();
img.src = 'http://somedomain.com/image.jpg';
......
//cancel load
img.src = '';
Yes, page is downloaded twice on Android when an img tag has an src="" attribute.
This still occurs on recent Android versions.
I have not found any other browser that does that.
But I found a solution: use an img tag without src attribute.
The ultimative answer is web workers.
Load the image inside an webworker and stopping the web worker will stop the image loading.
You can get the idea from this code:
https://github.com/NathanWalker/ng2-image-lazy-load
this work for me:
imageVarName.src = '';
imageVarName.onload = null;
imageVarName.onerror = null;
the src property must be a valid non-empty URL
So null or empty string are not legal (even though they sometimes work).
Use:
img.src='http://xxxx';
img.onerror=null;
(see here)
Sadly, setting src to an empty string does not work in WebKit-based browsers like Safari. Here is the link to the bug report which Stella mentioned.
https://bugs.webkit.org/show_bug.cgi?id=6656

Categories

Resources