I have an html paragraph (inside a div) in which I want to display a simple fixed text. The text is a bit long so I'd rather the text will be in a seperate txt file.
something like
<div><p txt=file.txt></p></div>
Can I do something like that?
You can do something like that in pure html using an <object> tag:
<div><object data="file.txt"></object></div>
This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width and height manually. And styles won't be applied to the text.
You can use a simple HTML element <embed src="file.txt"> it loads the external resource and displays it on the screen no js needed
It can be done with HTML <embed> or <object> tags, Javascript, or PHP/ASP/other back-end languages.
PHP (as example of server-side language) is the the way I've always done it:
<div><p><?php include('myFile.txt'); ?></p></div>
To use this (if you're unfamiliar with PHP), you can:
1) check if you have php on your server
2) change the file extension of your .html file to .php
3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file
Javascript will do the trick here.
function load() {
var file = new XMLHttpRequest();
file.open("GET", "http://remote.tld/random.txt", true);
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
document.getElementById("div1").innerHTML = text;
}
}
}
}
window.onLoad = load();
I would use javascript for this.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4 && txtFile.status == 200) {
allText = txtFile.responseText;
}
document.getElementById('your div id').innerHTML = allText;
This is just a code sample, would need tweaking for all browsers, etc.
Here is a javascript code I have tested successfully :
var txtFile = new XMLHttpRequest();
var allText = "file not found";
txtFile.onreadystatechange = function () {
if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
allText = txtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('txt').innerHTML = allText;
}
txtFile.open("GET", '/result/client.txt', true);
txtFile.send(null);
Related
I have an html paragraph (inside a div) in which I want to display a simple fixed text. The text is a bit long so I'd rather the text will be in a seperate txt file.
something like
<div><p txt=file.txt></p></div>
Can I do something like that?
You can do something like that in pure html using an <object> tag:
<div><object data="file.txt"></object></div>
This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width and height manually. And styles won't be applied to the text.
You can use a simple HTML element <embed src="file.txt"> it loads the external resource and displays it on the screen no js needed
It can be done with HTML <embed> or <object> tags, Javascript, or PHP/ASP/other back-end languages.
PHP (as example of server-side language) is the the way I've always done it:
<div><p><?php include('myFile.txt'); ?></p></div>
To use this (if you're unfamiliar with PHP), you can:
1) check if you have php on your server
2) change the file extension of your .html file to .php
3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file
Javascript will do the trick here.
function load() {
var file = new XMLHttpRequest();
file.open("GET", "http://remote.tld/random.txt", true);
file.onreadystatechange = function() {
if (file.readyState === 4) { // Makes sure the document is ready to parse
if (file.status === 200) { // Makes sure it's found the file
text = file.responseText;
document.getElementById("div1").innerHTML = text;
}
}
}
}
window.onLoad = load();
I would use javascript for this.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4 && txtFile.status == 200) {
allText = txtFile.responseText;
}
document.getElementById('your div id').innerHTML = allText;
This is just a code sample, would need tweaking for all browsers, etc.
Here is a javascript code I have tested successfully :
var txtFile = new XMLHttpRequest();
var allText = "file not found";
txtFile.onreadystatechange = function () {
if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
allText = txtFile.responseText;
allText = allText.split("\n").join("<br>");
}
document.getElementById('txt').innerHTML = allText;
}
txtFile.open("GET", '/result/client.txt', true);
txtFile.send(null);
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);
}
To create download button I normally use:
<button></button>
Is there any way to define myfile = url-to-the-file so that I can use just:
<button></button>
Per my comment, I'm not sure why you would want to do this, but for example you could replace the short text with the real links fairly easily. Just as a very basic example (http://jsfiddle.net/7vbv9oxc/):
HTML:
<button>
Click
</button>
JS:
var links = {
googs: "http://google.com"
}
// jQuery but vanilla JS shouldn't be hard
$('a').each(function(){
var $this = $(this);
var shortLink = $this.attr('href');
if(typeof(links[shortLink]) !== "undefined") {
$this.attr('href', links[shortLink]);
}
});
Alternatively, you could do the substitution at click time, saving iterating over all the anchor tags.
$('a').on('click', function(e) {
var $this = $(this);
var shortLink = $this.attr('href');
if(typeof(links[shortLink]) !== "undefined") {
$this.attr('href', links[shortLink]);
}
});
We don't prevent default (or return false) because we WANT it to act like a normal anchor, but after the swap has been made. If you want to do something different before loading or redirecting the target URL, you would add an e.preventDefault() to that code block.
Note (for my own peace of mind!) that none of this code is meant to represent optimizations or best practices; it's just meant to illustrate the idea. For example, you would probably want to put the click listener on an ancestor!
I'd like to dump the HTML contents of a web page, including the HTML of iframes included inside the <iframe> elements. The Chrome Developer Tools "Elements" tab is capable of showing iframe embedded in this way.
When I say "dump the HTML contents" I'm interested in browser automation tools like Selenium or PhantomJS. Do any of these tools have this capacity built in?
For example, the HTML dump I'd like of this page should include the HTML source of this embedded page.
You can use phantomjs to achieve this
Here is a code snippet from the phantom js server code.
var system = require('system');
var url = system.args[1] || '';
if(url.length > 0) {
var page = require('webpage').create();
page.open(url, function (status) {
if (status == 'success') {
var delay, checker = (function() {
var html = page.evaluate(function () {
var body = document.getElementsByTagName('body')[0];
if(body.getAttribute('data-status') == 'ready') {
return document.getElementsByTagName('html')[0].outerHTML;
}
});
if(html) {
clearTimeout(delay);
console.log(html);
phantom.exit();
}
});
delay = setInterval(checker, 100);
}
});
}
on the html you use the "data-status" attribute to let phantomjs know when the page is ready if the html belongs to you . The other option would be to use a nice timeout if the html page does not belong to you.
From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working
<div id="divContainer">
<h3>Sample title</h3>
</div>
<button onclick="clicker()">Click me</button>
<script type="text/javascript">
function clicker() {
var anchorTag = document.createElement('a');
anchorTag.href = "http://cdn1.dailymirror.lk/media/images/finance.jpg";
anchorTag.download = "download";
anchorTag.click();
var element = document.getElementById('divContainer');
element.appendChild(anchorTag);
}
</script>
Internet Explorer does not presently support the Download attribute on A tags.
See http://caniuse.com/download and http://status.modern.ie/adownloadattribute; the latter indicates that the feature is "Under consideration" for IE12.
In my case, since there's a requirement to support the usage of IE 11 (version 11.0.9600.18665), I ended up using the solution provided by #Henners on his comment:
// IE10+ : (has Blob, but not a[download] or URL)
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(blob, fileName);
}
It's quite simple and practical.
Apparently, this solution was found on the Javascript download function created by dandavis.
Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.
downloadCSV(data,fileName){
var blob = new Blob([data], {type: "text/plain;charset=utf-8;"});
var anchor = angular.element('<a/>');
if (window.navigator.msSaveBlob) { // IE
window.navigator.msSaveOrOpenBlob(blob, fileName)
} else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
anchor.css({display: 'none'});
angular.element(document.body).append(anchor);
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
target: '_blank',
download: fileName
})[0].click();
anchor.remove();
} else { // Chrome
anchor.attr({
href: URL.createObjectURL(blob),
target: '_blank',
download: fileName
})[0].click();
}
}
Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.
As of build 10547+, the Microsoft Edge browser is now supporting the download attribute on a tags.
Download Image
Edge features update: https://dev.windows.com/en-us/microsoft-edge/platform/changelog/desktop/10547/
a[download] standard: http://www.w3.org/html/wg/drafts/html/master/links.html#attr-hyperlink-download
This code fragment allows saving blob in the file in IE, Edge and other modern browsers.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
// Extract filename form response using regex
var filename = "";
var disposition = request.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
if (window.navigator.msSaveOrOpenBlob) { // for IE and Edge
window.navigator.msSaveBlob(request.response, filename);
} else {
// for modern browsers
var a = document.createElement('a');
a.href = window.URL.createObjectURL(request.response);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
}
button.disabled = false;
dragArea.removeAttribute('spinner-visible');
// spinner.style.display = "none";
};
request.open("POST", "download");
request.responseType = 'blob';
request.send(formData);
For IE and Edge use: msSaveBlob
Use my function
It bind your atag to download file in IE
function MS_bindDownload(el) {
if(el === undefined){
throw Error('I need element parameter.');
}
if(el.href === ''){
throw Error('The element has no href value.');
}
var filename = el.getAttribute('download');
if (filename === null || filename === ''){
var tmp = el.href.split('/');
filename = tmp[tmp.length-1];
}
el.addEventListener('click', function (evt) {
evt.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onloadstart = function () {
xhr.responseType = 'blob';
};
xhr.onload = function () {
navigator.msSaveOrOpenBlob(xhr.response, filename);
};
xhr.open("GET", el.href, true);
xhr.send();
})
}
Append child first and then click
Or you can use window.location= 'url' ;
As mentioned in earlier answer , download attribute is not supported in IE . As a work around, you can use iFrames to download the file . Here is a sample code snippet.
function downloadFile(url){
var oIframe = window.document.createElement('iframe');
var $body = jQuery(document.body);
var $oIframe = jQuery(oIframe).attr({
src: url,
style: 'display:none'
});
$body.append($oIframe);
}
I copied the code from here and updated it for ES6 and ESLint and added it to my project.
You can save the code to download.js and use it in your project like this:
import Download from './download'
Download('/somefile.png', 'somefile.png')
Note that it supports dataURLs (from canvas objects), and more... see https://github.com/rndme for details.