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.
Related
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">
I'm having issues with developing my Google Chrome extension. I need some specific npm modules in order to execute my code so I looked into Browserify. I followed all the steps without issue but the code still produces errors when run. The screenshot is attached below.
Error when Chrome extension is only loaded
All my files are located in the same project folder (popup.html, popup.js, bundle.js, etc.). I only have one html file and one javascript file (excluding bundle.js).
Here is my popup.html code:
document.addEventListener('DOMContentLoaded', function() {
var convertMP3Button = document.getElementById("getLinkAndConvert");
convertMP3Button.addEventListener("click", function() {
chrome.tabs.getSelected(null, function(tab) { // 'tab' has all the info
var fs = require('fs');
var ytdl = require('ytdl-core');
var ffmpeg = require('fluent-ffmpeg');
var ffmetadata = require("ffmetadata");
var request = require('request');
console.log(tab.url); //returns the url
convertMP3Button.textContent = tab.url;
var url = tab.url;
var stream = ytdl(url);
//.pipe(fs.createWriteStream('/Users/nishanth/Downloads/video.mp4'));
// Helper method for downloading
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
ytdl.getInfo(url, function(err, info) {
console.log("INFO: " + JSON.stringify(info, null, 2));
var process = new ffmpeg({source:stream})
process.save('/Users/nishanth/Downloads/' + info.title + '.mp3').on('end', function() {
console.log("PROCESSING FINISHED!");
download(info.thumbnail_url, "/Users/nishanth/Downloads/image.jpg", function() {
console.log("DOWNLOADED IMAGE");
var options = {
artist: info.author,
attachments: ["/Users/nishanth/Downloads/image.jpg"]
};
ffmetadata.write('/Users/nishanth/Downloads/' + info.title + '.mp3', {}, options, function(err) {
if (err)
console.error("Error writing cover art: " + err);
else
console.log("Cover art added");
});
});
});
});
});
});
});
<!doctype html>
<html>
<head>
<title>Youtube Music</title>
<script src="bundle.js"></script>
<script src="popup.js"></script>
</head>
<body>
<h1>Youtube Music</h1>
<button id="getLinkAndConvert">Download Song Now!</button>
</body>
</html>
It would be great if I could find out the reason why I have not been able to properly integrate browserify in order to use the npm modules.
Browsers don't allow you to access the file system, instead they usually have some storage mechanisms of their own (cookies, localstorage, or a browser-specific system like chrome.storage). Browserify has no way of getting around this, and doesn't provide a shim for require('fs'). Instead of writing directly to disk you'll need to have your app provide a downloadable version of your files, which the user will then have to save manually. If you don't need the files to be accessible outside the extension you can use the api I linked earlier, or drop in something like browserify-fs which creates a virtual file system in the browser's storage.
I'm creating a script like twitter in which user just provide an id and all his/her tweets get loaded on site where the script inserted.
What I've done is
User should copy this code to load my widget
<a class="getStarted" data-getStartedID="123456789">Get Started App ID</a>
<script>
!function(d,s,id){
var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';
if(!d.getElementById(id)){
js=d.createElement(s);
js.id=id;
js.src=p+"://localhost/practices/js_practice/siteOpen.js";
fjs.parentNode.insertBefore(js,fjs);
}}(document,"script","getStarted-C");
My siteOpen.js is as below :
!function(d){
var a = d.getElementsByClassName('getStarted');
var x = document.getElementsByClassName("getStarted")[0].getAttribute("data-getStartedID");
var r = new XMLHttpRequest();
var appID = x;
r.open("POST", "openwebIndex.php", true);
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", appID.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
if(r.responseText.trim()==1){
return '<p>output to be draw on where script is pasted</p>';
if(console)console.info('Valid appID');
}
};
r.send('appID='+appID);
}(document);
i don't know what to do to send the response and load/draw my widget on user's website.
My response will be in html elements.
Please suggest me what should i do. I just stuck at this point.
EDIT
I'm getting object HTMLScriptElement when I alert js variable.
Just trying adding the html code in the body tag.
users html file
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
<script src="widget.js"></script>
Your widget.js
// var appId = d.getElementsByClassName('getStarted');
// process the app id and make the output here
var output = "<div>This is the content of the widget</div>";
document.body.innerHTML += output;
This will show the content in the users html file. If you have cross domain issue, use JSONP for resolving that.
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;
})();