EDIT:
I do not want to save to a text file.... I want the user to be able to select their own file and use the variables within that file.
I would like to have the user upload their own "settings.js" file and then the page use the variables once loaded.
How would I change my code to reflect this?
At present I have the following javascript file and HTML code:
Javascript File: settings.js
var myVariable = 6000;
HTML file: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Load Javascript file</title>
</head>
<body>
<script src="settings.js"></script>
<div>
<script>
alert(myVariable)
</script>
</div>
</body>
</html>
Please help.
something like this maybe
document.getElementById("settings").addEventListener("change", function(){
if(this.files[0] && this.files[0].type == "text/javascript"){
var reader = new FileReader();
reader.onload = function (e) {
var settings = e.target.result.split("data:text/javascript;base64,")[1];
eval(atob(settings));
//use the loaded var's
document.getElementById("result").innerText = myVariable;
}
reader.readAsDataURL(this.files[0]);
}
});
<input type="file" id="settings">
<div id="result"></div>
Here is a full working code for you.
It will read file and print it as text for debugging on the screen and will add the file as script file to the page as well.
<!DOCTYPE HTML>
<html>
<head>
<script>
function loadScript() {
var inputFile = document.querySelector("#scriptFile"),
// Get the selected file
file = inputFile.files[0],
// HTML5 File API
fileReader = new FileReader();
// Add the onload event to the file
fileReader.onload = printFile;
// Read the file as text
fileReader.readAsText(file);
function printFile( reader ) {
// Get the text of the file
var content = reader.target.result,
script;
// Add the fileContent as script to the page
script = document.createElement('script');
script.textContent = content;
document.body.appendChild(script);
///////////////// DEBUG
var pre = document.createElement('pre');
pre.textContent = content;
document.body.appendChild(pre);
}
}
</script>
</head>
<body>
<input type='file' id='scriptFile'>
<input type='button' value='Load' onclick='loadScript();'>
</body>
</html>
This code will run javascript stored in your JS file. Use FileReader() to read file as text, and use eval(content); to execute that code. If you can execute JavaScript you can do anything you want. Use only variables, or anything else.
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
//Here the content has been read successfuly
eval(content);
}
reader.readAsText(file);
} else {
document.innerText = "File not supported!"
}
});
<input type="file" id="fileInput">
Related
I want adding and running external javascript file in new window.open() , so I tested the solution in Running Javascript in new window.open , but this solution doesn't work.
My code is here :
<input type="button" value="Open a window" onclick="openWindow();">
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script');
//Add external javascript file in src attribut of script tag :
script.src = "script.js";
//Append script tag to the new window :
win.document.head.appendChild(script);
}
</script>
The content of external javascript file called script.js is :
alert("It works !");
When you click the button, a new window is opened, but the external javascript file added is not executed.
So how to run the external javascript file added in new window opened ?
Use document.write
const win = window.open('')
win.document.open()
const html = `
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"><\/script>
</head>
<body>
<h1>Test</h1>
<script>alert($('h1').text())<\/script>
</body>
</html>
`
win.document.write(html)
win.document.close()
Try this
<script type="text/javascript">
function openWindow()
{
//Open a new window :
var win = window.open("");
//Create script tag :
var script = document.createElement('script'),
div = document.createElement('div');
//Add external javascript file in src attribut of script tag :
script.src = "https://cdnjs.cloudflare.com/ajax/libs/preact/8.3.1/preact.min.js";
script.type = "application/javascript";
script.defer = true;
div.appendChild(script);
win.document.body.appendChild(div);
}
</script>
In the new window open developer console and type preact you will see output like {h: ƒ, createElement: ƒ, cloneElement: ƒ, Component: ƒ, render: ƒ, …}
I am trying to print a pdf with PDF.js but currently I cannot get the document data rendered in the pdf element. This is what it looks like right now:
So, no data is being rendered.
This is the code behind:
<script src="jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="pdf.js"></script>
<script type="text/javascript" src="pdf.worker.js"></script>
<body id="printbody" style="margin:0px;">
</body>
<script type="text/javascript">
var pdfData = atob('JVBERi0xLjQK...'); //Shortened
PDFJS.workerSrc = 'pdf.worker.js';
PDFJS.getDocument({data: pdfData}).then(function RenderAndPrint(res) {
var src = URL.createObjectURL(new Blob([res], { type: 'application/pdf' }))
var printFrame = document.createElement('iframe');
printFrame.id = 'print-frame';
//printFrame.style.display = 'none';
printFrame.style.width = '100%'
printFrame.style.height = '100%'
printFrame.style.border = 'none'
printFrame.src = src;
document.body.appendChild(printFrame);
setTimeout(function () {
printFrame.contentWindow.print();
}, 0)
});
</script>
The final goal is to have this entire page appended to an existing page via AJAX so the as soon as the this page is appended and renders the PDF, the iframe (which would be hidden) would print the pdf as soon as it renders and then eventually dispose of itself.
I was using itextsharp, I instead saved the pdf to the local system, set it to print on open like so:
PdfAction print = new PdfAction(PdfAction.PRINTDIALOG);
writer.SetOpenAction(print);
and then used an iframe to render the pdf by setting the file to the src
I just found a working docx to html converter using only javascript on github. The main code which converts docx to html is below. The issue is the page just has a button which on click or drag and choosing a word document, opens it as html. I want to specify a file location in the code so I can load it on the server for loading some documents from computer locally.
Code which converts docx to html and renders :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DocxJS Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://www.docxjs.com/js/build/latest.docxjs.min.js"></script>
</head>
<body>
<input id="inputFiles" type="file" name="files[]" multiple="false">
<div id="loaded-layout" style="width:100%;height:800px;"></div>
<script>
$(document).ready(function(){
var $inputFiles = $('#inputFiles');
$inputFiles.on('change', function (e) {
var files = e.target.files;
var docxJS = new DocxJS();
docxJS.parse(
files[0],
function () {
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
</script>
</body>
</html>
I tried changing var files = e.target.files; to var files = "C:/sda/path/to/docx"; but that didn't help.
I tried to change
var files = e.target.files;
to
var files = new Array(new File([""], "sample.docx"));
but it gives me OOXML parse error.
Update:
Lets say I have a file location variable in PHP and I wish to use that instead in the javascript code. How do I do it?
I also checked docx2html javascript code and here is the code for it:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
<script>
function test(input){
require("docx2html")(input.files[0]).then(function(converted){
text.value=converted.toString()
})
}
</script>
</head>
<body>
<input type="file" style="position:absolute;top:0" onchange="test(this)">
<br/>
<br/>
<textarea id="text"></textarea>
</body>
</html>
Same issue need input.files[0] here as well
Update:
I am trying to use the method mentioned in the comments but encounter some errors:
var fil;
var getFileBlob = function (url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, 'test.docx'));
});
};
getFileObject('demo.docx', function (fileObject) {
console.log(fileObject);
fil = fileObject;
});
The error primarily was “Cross origin requests are only supported for HTTP.” before I used https://calibre-ebook.com/downloads/demos/demo.docx instead of just demo.docx in above file path. This however gives another error:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
which means chrome cannot load it. It needs to be working on a server. If someone can help providing a fix to make it work offline, let me know. The last method was asynchronous call.
In the browser, there is a sandbox policy.
It can not access files directly via Path.
Please access the file through drag & drop event or input file change event.
i am making an application in which i need to directly pick up the .doc or .docx files from the file system and load them on the page. Can you help me with the code ?
There is a problem with using a normal file reader in opening these files , can anyone clarify why is it happenning ?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs'
if required -->
<body>
<input type="file" id="files" name="file" />
<div id="byte_content"></div>
<script>
function readBlob() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
$("document").ready(function () {
$("#files").change(function () {
readBlob();
});
});
</script>
</body>
</html>
You could take a look at the DocumentCloud project which has a bunch of components including an HTML5 Open Source Document viewer - NYtimes Document viewer - hosted on git (Apache license)
I'm a new programmer that learn javascript, Im new in js actually.
I have a task that require a web page able to read file in client directory. I've got some js code :
<html>
<script type="text/javascript">
function ReadWeight() {
var filePath = "file:///D:/Text.txt";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
alert(fileContent);
}
ReadWeight();
</script>
<body>
</body>
</html>
When I save this code in my directory and access it by this link, It works well.
file:///D:/test.html
But when I put it in my localhost and I access it, the JS doesn't works.
Does my code incorrect when in web server?
Please help me out.
Might I suggest using an error console to display the error so people know how to help you? =] And paste it in your query
Download something like firebug and see if a request is being made (for FireFox)
It looks like you would rather want to access the file via the http:// protocol, instead of file://
As far as I know you can only read client files using an <input type="file"> element. Once you get the file you can read it multiple times:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Refresh</title>
<script src="filerefresh.js"></script>
</head>
<body>
<input id="fileInput" type="file">
<pre id="fileDisplay"></pre>
</body>
</html>
JavaScript:
(function() {
var sleepInterval = 1000; // 1 second
var fileInput;
var fileDisplay;
var reader;
var id = undefined;
function initialize() {
fileInput = document.getElementById("fileInput");
fileDisplay = document.getElementById("fileDisplay");
reader = new FileReader();
reader.onloadend = function() {
fileDisplay.innerHTML = reader.result;
reschedule();
};
fileInput.addEventListener("change", readFile);
}
function reschedule() {
if (id !== undefined) {
clearTimeout(id);
}
id = setTimeout(readFile, sleepInterval);
}
function readFile() {
reader.readAsText(fileInput.files[0]);
}
window.onload = initialize;
})();