Is AJAX allowed between files that are inside the same app project?
Is this allowed in the 5 main browsers?
Should I use any specific header, or any $.ajax(~) special property to specify my intentions?
I will use Phonegap, by the way.
Thank you a lot.
Yes. Your app runs a local website on your device. Relative file urls work fine
xhr = new XMLHttpRequest();
xhr.open('GET', 'page.html', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
xhr.status === 200 ? success() : failure();
}
};
xhr.send();
Related
When a div is clicked on my site, I want the contents of another html file to be added to the existing html. I've tried many methods and cannot find a solution. I don't want to use iframe or object or jquery or php.
function loadhtmlfile(filename, filetype, location){
var fileref=document.createElement('link');
fileref.setAttribute("rel", "html");
fileref.setAttribute("type","text/html");
fileref.setAttribute("href", filename);
document.getElementById("parentDiv").appendChild(fileref);
}
loadhtmlfile("my.html", "html", "parentDiv");
This adds a link for the html file. It doesn't add the actual content of the html file.
Also from what I've read, it sounds like it may be best to do this using a server application. I'm using node.js. If it's best doing this server side, how do I do this using node.js?
Also I will be using websockets so I suspect this will change answers.
You just could use XMLHttpRequest with javascript to load HTML content :
function loadFile(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file);
xhr.addEventListener('readystatechange', function() { // load the page asynchronously
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // if the file is correctly loaded
document.getElementById('yourelement').innerHTML = xhr.responseText;
}
});
xhr.send(null);
}
I can have the user upload a file on a webpage using <input type='file' accept='text/plain' onchange='ReadTheTextfile(event)'>.
and then use javascript: FileReader,
reader.readAsText(event.target.files[0]); etc
but I already know that I want to read a file, which I already uploaded to the webserver.
How can I determine by myself which file I want to upload / read ? XMLHttpRequest ?
I don't want to read a file from the user's pc.
I want to read a file from the server, where my html files are also hosted.
You can retrive it via ajax call as follows.
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
Reference - https://stackoverflow.com/a/13329900/9640177
This question already has answers here:
How can I create download link in HTML?
(12 answers)
Closed 1 year ago.
<a download='file' href="https://tinyjpg.com/images/social/website.jpg">
Download
</a>
Is there a way to force the download of a file instead of opening the file in a new window? Right now if the file is a URL, like the example below it won't be downloaded and will open in a new window.
You may be bitten by the fact that Firefox and Chrome 65+ only support same-origin download links, probably as a security measure.
Source: https://caniuse.com/#feat=download (see "Known issues" tab)
The Web Hypertext Application Technology Working Group (WHATWG) recommends that in cross-origin scenarios (as in your example), the web server that is hosting the image/file in question needs to send a Content-Disposition HTTP header for download= to be honored.
Source: https://html.spec.whatwg.org/multipage/links.html#downloading-resources
In short:
You can only use <a download='...'></a> to force download of an image/file, if:
the html and the image/file are hosted on the same domain,or
the image/file is on a different domain, and that server also says it should be downloaded.
Maybe you have solved in the meanwhile, but since you are hosting the files on S3 (see comments on Peter B's answer), you need to add a signature to the files url and set the ResponseContentType to binary/octet-stream by using the aws sdk. I am using Node so it becomes:
const promises = array.map((item) => {
const promise = s3.getSignedUrlPromise('getObject', {
Bucket: process.env.S3_BUCKET,
Key: key, //filename
Expires: 604800, //time to expire in seconds (optional)
ResponseContentType: 'binary/octet-stream'
});
return promise;
});
const links = await Promise.all(promises);
I hope this helps.
setTimeout(function() {
url = 'https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png';
// downloadFile(url); // UNCOMMENT THIS LINE TO MAKE IT WORK
}, 2000);
// Source: http://pixelscommander.com/en/javascript/javascript-file-download-ignore-content-type/
window.downloadFile = function (sUrl) {
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
//alert('Your device does not support files downloading. Please try again in desktop browser.');
window.open(sUrl, '_blank');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
link.setAttribute('target','_blank');
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
if (sUrl.indexOf('?') === -1) {
sUrl += '?download';
}
window.open(sUrl, '_blank');
return true;
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
You can use this function to downlaod images using fetch
async function downloadImage(imageSrc) {
const image = await fetch(imageSrc)
const imageBlog = await image.blob()
const imageURL = URL.createObjectURL(imageBlog)
const link = document.createElement('a')
link.href = imageURL
link.download = 'image file name here'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
Your link should have an ID to force download:
<a download='website.jpg' id='blablabla' href="https://tinyjpg.com/images/social/website.jpg">
Download
</a>
Working in HTML/SCSS/JQUERY.
Want to link to a webpage but if it's a broken link that it will load the saved .mht version.
Another user provided this code in other thread of this forum to chek if a link is broken (JavaScript/jQuery check broken links)
function urlExists(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.status < 400);
}
};
xhr.open('HEAD', url);
xhr.send();
}
urlExists(someUrl, function(exists) {
console.log('"%s" exists?', someUrl, exists);
I want to include some files in my crx and then be able to read them in as data (into a string or Blob). How would I do this? Is there a way to use the FileSystem API for this?
chrome.runtime.getPackageDirectoryEntry was implemented on 2013-06-13, expected in Chrome 29:
Issue 177208: add read-only FileSystem API for access to packaged app/extension resources
Change: https://chromiumcodereview.appspot.com/16470003
Read file contents from crx via XHR is much more simple than FileSystem API:
var url = chrome.extension.getURL('the_file.txt'); // full url
var req = new XMLHttpRequest(); // read via XHR
req.open('GET', url);
req.onreadystatechange = function(e) {
if (req.readyState === 4 && req.status === 200) {
console.log(data);
} else {
// error
}
}
If you want to make the request in an injected context, you must have accessable resources declared in manifest.json first, list filename (support wildcards) in accessible resources entry.
"web_accessible_resources": [
"path_to_the_file.html",
"just_another_folder/*.txt"
]