jQuery - Read data from text file with .get/.load - force reload? - javascript

I want to load data from a web server with jQuery. I'm uploading a file to a web server, put the response (which is containing a link) to an iframe and read this link with .get(). When I now upload another file, which leads to the same filename but changed contents, .get() does not read the content correctly on the first try, but reliable on the second. .load() should do basically the same, but does not reload the file no matter how often I re-upload the file.
Is there a chance to force the reload of the changed file?
var linkToTextFile = 'http://www.myserver.com/myTextFile.txt';
$.get(linkToTextFile, function(data){
alert("Data:" + data); //content changes on second try
});

Try to append a random GET parameter to your text file's URL :
var timestamp = new Date().getTime();
var linkToTextFile = 'http://www.myserver.com/myTextFile.txt?t=' + timestamp;
This way it will force the browser to reload the file.

Related

Downloading a file from a dynamically generated Blob URL

Summary:
I am trying to write a bookmarklet that automatically downloads all my receipts from a certain hotel website. I'm able to open a new tab with the PDF showing, but having trouble actually getting that file data and saving it locally.
What I've done/tried:
I've been able to get the bookmarklet to traverse through the page, and find the right element, and even obtain a link to the PDF. I've also been able to open that link in a new window where the PDF loads successfully. If I put a settimeout on loading that tab, I can even get the blob URL as well.
The problem is - once I have the blob URL - I'm not sure how to actually save it. Also - I'm not sure I actually can, because if I try to manually open a new tab and paste the same blob URL in there, I get a 404 not found (which makes me think the URL is a single-use only.
Code:
document.getElementsByClassName('aa-items past-activities--items')[0].getElementsByTagName('button')[0].click()
path_to_pdf = document.getElementsByClassName('aa-items past-activities--items')[0].getElementsByClassName('hotel-rebook')[0].querySelectorAll("[data-locator='hotel-bill']")[0].href
newwindow = window.open(path_to_pdf)
function checkLoad()
{
if (newwindow.location.href.includes('blob'))
{
path_to_pdf_blob = newwindow.location.href
console.log(path_to_pdf_blob)
newwindow.close()
} else {
setTimeout('checkLoad();', 1000)
}
}
checkLoad()

Replace image with the same path not working after second time in Html/Javascript

I have an application in Asp.net Core MVC in which user upload his profile image. The server side is working fine but at client side when i change the image src for first upload, it works fine but after second time the image replaced at server but at client side it shows the same. That's how i am changing the src of an image.
var src = "/up_images/profiles/" + result.data;
$("#profileImage").attr("src", src);
please note that i am replacing the existing image. In this case if src is "/up_images/profiles/137.jpg" then after uploading image the src will be the same. "137" is the user id.
if i refresh the page the image changes too.
also i have tried with some delay using timeout but it is not working.
What is the issue?
If the image path is exactly the same but resource changes, you'll want to force the request. That can easily be done by appending a query such as the current time.
$("#profileImage").attr("src", src + "?" + Date.now());
Or with template literals
$("#profileImage").attr("src", `${src}?${Date.now()}`);
You can try appending a query parameter that changes for each request, onto the end of the URL. It will get ignored by the server side, but the browser will treat it as a new request and not re-use the cached image.
Something like this:
var src = "/up_images/profiles/" + result.data + "?v=" + Date.now();
$("#profileImage").attr("src", src);

How to load cached Image in browser

Actually, I have a website which is taking time to retrieve the User Profile Picture from the Firebase server and I want to know If there is any way by which I can cache the image and use it next time the website is loaded.
The code I am using for retrieving the image from firebase is-
firebase.database().ref("/" + uid).child('userId').on('value', function(snapshot){
var storeTheUserId=snapshot.val();
var storageRef=firebase.storage().ref();
var setTheChild=storageRef.child(storeTheUserId + '.png')
setTheChild.getDownloadURL().then(function(url){
document.getElementById('userProfilePicture').src=url;
});
});
I just want to use the cached Image and use it next time when the website is loaded.

Chrome blocking PDF views on web redirection to new tab via Top-Frame Navigations

As per the Chrome version >=60 the PDF view functionality by any top-frame navigations options like
<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”
has been blocked by Google for which the discussion can be found at Google Groups. Now the problem is how to display the PDF on web without explicitly or forcibly making PDF to download. My old code looked as below via window.open to view the PDF data
dataFactory.getPDFData(id, authToken)
.then(function(res) {
window.open("data:application/pdf," + escape(res.data));
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
In above I extract the PDF data from server and display it. But since window.open is blocked by Chrome and as suggested by one of the expert over here to use <iframe> to open the PDF data and I tried but it's not working. It always says Failed to Load PDF Data as below
The updated JS code for the <iframe> looks as below:
dataFactory.getPDFData(id, authToken)
.then(function(res) {
$scope.pdfData = res.data;
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
And the HTML looks as below:
<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>
How can I proceed and bring back the original PDF view functionality? I searched over other stack questions but out of luck on how to resolve this. May be I did something wrong or missed something with the iframe code but it's not working out.
After unable to find the desired result I came up with below approach to resolve the issue.
Instead of opening the PDF on new page what I did is as soon as user clicks on the Print button PDF file gets downloaded automatically. Below is the source for same.
//File Name
var fileName = "Some File Name Here";
var binaryData = [];
binaryData.push(serverResponse.data); //Normal pdf binary data won't work so needs to push under an array
//To convert the PDF binary data to file so that it gets downloaded
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();
//To remove the inserted element
window.onfocus = function () {
document.body.removeChild(fileURL)
}
In your old code :
"data:application/pdf," + escape(res.data)
In the new :
your iframe src is like "data:application/pdf;base64,pdfData"
Try to remove base64 from the src, it seems to be already present in the value of 'pdfdata'.

Creating download prompt using purely javascript

I have some text data (say var a = 'Hello World From Javascript';)in javascript variable in current window. I want to do the following
through javascript-
1. open a new window and write the text data to the window.
2. set the content type to text/plain.
3. set the content-disposition to attachment, so that download prompt comes.
4. user downloads the text data as a text file and saves it to his local disk.
is this all possible through javascript?
I know we can make ajax calls to server or redirect but in this case instead of following above steps. But in this case, these workarounds are not adaptable.
you can do that using JS & HTML5 features. Please find below a sample code.
var fileParts = ['Hello World From Javascript'];
// Create a blob object.
var bb = new Blob(fileParts,{type : 'text/plain'});
// Create a blob url for this.
var dnlnk = window.URL.createObjectURL(bb);
var currentLnk = $('#blobFl').attr('href');
// blobFl is the id of the anchor tag through which the download will be triggered.
$('#blobFl').attr('href',dnlnk);
$('#blobFl').attr('download','helloworld.txt');
// For some reason trigger from jquery dint work for me.
document.getElementById('blobFl').click();
Triggering a file download without any server request
Unfortunately this is not something you can do with normal browser capabilities. Something like flash or a browser-specific plugin will get you what you need, but security limitations within javascript will not let you download arbitrary data created within the browser.
Also the 'data' url is not supported across all browser/version combinations. I am not sure if your users are constrained on what browser they are using or not but that may limit what you can do with that solution.
Source: Triggering a file download without any server request
If you already have the file on the server (I make an ajax call to generate and save a PDF on the server) - you can do this
window.location.replace(fileUrl);
No, Content-Disposition is a response header, it has to come from the server. I think you could do it with Flash but I wouldn't recommend it.
Here's a clean, pure js version of #Rajagopalan Srinivasan's answer:
var fileParts = ["Hello World From Javascript"];
// The anchor tag to use.
const blobLink = document.getElementById("blobLink");
// Create a blob object.
var blob = new Blob(fileParts, { type: "text/plain" });
// Create a blob url for this.
var blobUrl = window.URL.createObjectURL(blob);
blobLink.setAttribute("href", blobUrl);
blobLink.setAttribute("download", "helloworld.txt");
blobLink.click();
<a id="blobLink">Download</a>

Categories

Resources