I've just watched the mozilla File API file reading as
new FileReader();
etc. and I must ask is there something like that for IE?
Yes, you can use ActiveX' FileSystemObject. However, an confirmation box is shown to the user everytime he runs the code. Some users might not trust you and could choose not to run the ActiveX control.
Also, please note that some users also use non-IE browsers which don't support FileReader (Safari, older versions of Firefox and so on). By adding ActiveX, you still won't have 100% support for file-related APIs.
Internet Explorer 10 also supports the FileReader:
var reader = new FileReader();
reader.onloadend = function(){
// do something with this.result
}
reader.readAsText(readFile);
For managed compatability tables regarding the FileReader, be sure to check out caniuse.com.
If you wanted to provide a fall-back for those who may not be visiting your site in Internet Explorer 10, I would encourage you to do a bit of feature-detection to determine whether or not you want to use the FileReader:
if ( window.FileReader ) {
/* Use the FileReader */
} else {
/* Do something else */
}
Note also that using an ActiveXObject approach isn't necessarily going to work all the time either as some users browse with ActiveX Filtering enabled, meaning you can't touch their file-system, or run any types of plugins in their browser.
Related
According to my requirement I need to implement a filesystem using ActiveXObject in IE. I implemented the same but difficulty is that to ask users to enable the "initialize and script activex controls not marked as safe for scripting" option manually from Internet options. So can anyone please suggest me how to enable the same via coding(Javascript or batch).
NOT An Answer or solution, just some guidance based on brief experience in similar area. IE-11 doesn't allow ActiveX object anyway to be used directly unless IE security settings are lowered as you mentioned. Develop a plugin instead and have your users to install this plugin as a prerequisite to use your application.
Alternatively, here's a way you can try to instantiate an ActiveX object in your javascript BUT again this may well need IE settings to be manually set to allow ActiveX to be invoked or to run this javascript. You may need test this out.
xx
try {
var shellObj = new ActiveXObject("WScript.Shell");
var clsid = "xxxxxxxx-xxxx-xxxx-xxxx-000000000000";
var progid = shellObj.RegRead("HKEY_CLASSES_ROOT\\CLSID\\{" + clsid + "}\\ProgID\\");
var plugin = new ActiveXObject(progid);
if (plugin) {
//whatever you want to achieve
}
else {
return null;
}
}
I'm attempting to write some JavaScript code (in particular, a Chrome extension) which does the following:
Retrieve some web page's contents via AJAX.
Get some content from that page by locating certain elements inside of the HTML string and getting their contents.
Do a thing with that data.
I have 1) and 3) working, but I'm having some trouble achieving step 2) in a reasonable way.
I currently have 2) implemented via jQuery(htmlString) and then using normal jQuery selectors and etc. to extract the data I want. The problem is that jQuery actually adds the retrieved HTML to the current page, loading and executing all external resources / scripts in the process. This is obviously bad.
So I'm looking for a way to get the text and HTML in certain tags inside my HTML string without:
Loading or executing ANY scripts or resources (images, CSS, etc.) referenced in the HTML string.
Trying to remove external resources with regular expressions, since we all know what happens when you parse [X]HTML with regex.
I believe that I can achieve what I want using jsdom and jQuery, since jsdom has a FetchExternalResources option which can be set to false. However, jsdom seems to only work in NodeJS, not in the browser.
Is there any reasonable way to do this?
You could use document.implementation.createHTMLDocument
This is an experimental technology
Because this technology's
specification has not stabilized, check the compatibility table for
the proper prefixes to use in various browsers. Also note that the
syntax and behavior of an experimental technology is subject to change
in future versions of browsers as the spec changes
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 4.0 (2.0) [1] 9.0 (Yes) (Yes)
[1] The title parameter has only been made option in Firefox 23.
Javascript
$.ajax("http://www.html5rocks.com/en/tutorials/").done(function (htmlString) {
var doc = document.implementation.createHTMLDocument("");
doc.write(htmlString);
console.log(doc.getElementById('siteheader').textContent);
});
On jsFiddle
You can also take a look at DOMParser and XMLHttpRequest
Example using XMLHttpRequest
XMLHttpRequest originally supported only XML parsing. HTML parsing
support is a recent addition.
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Support 18 11 10 --- Not supported
Javascript
var xhr = new XMLHttpRequest();
xhr.onload = function () {
console.log(this.responseXML.getElementById('siteheader').textContent);
};
xhr.open("GET", "http://www.html5rocks.com/en/tutorials/");
xhr.responseType = "document";
xhr.send();
On jsFiddle
I've got a web page which needs to be able to load files into the DOM from the local machine on which the browser is running. I've found that this is very easy to do using the HTML 5 File API.
I can just do:
var reader = new FileReader();
reader.onload = function (fileContents) { ... load contents to a div ... }
reader.readAsText(f) //where f is an HTML5 File object
Annoyingly, I need this to work in IE7, and also some earlier versions of Firefox which don't support the API. Is there any easy way to load a local file into the DOM in older browsers?
Many thanks!
No, you cannot do that in older browsers. FileReader (any file system access really) is a new HTML5 feature which is not supported in older browsers.
Your best option in an older browser is either:
A Silverlight, Flash or Java app (or similar) that runs on the client-side and has local file system access.
Having the user upload files using the <input type="file"> element, and do your processing server-side.
Further to the other answers here, it does appear that there's no consistent way of doing this client-side (other than Flash) for older browsers.
For IE7/8 however, I've managed to hack something together using ActiveX.
var filePath = f:\oo.txt;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var textStream = fso.OpenTextFile(filePath);
var fileData = file.ReadAll();
I can then pass this to the same function as reader.onload in the question above. Obviously this is a bad, hacky solution, and liable to be blocked by some security policies - it does at least work for IE7 though!
Looks like you can do that through Flash. Flash alternative for FileReader HTML 5 API
if (window.ActiveXObject) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\Program Files\\GM4IE\\scripts\\source.txt","C:\\Program Files\\GM4IE\\scripts\\target.txt", 1);
fso = null;
}
catch (e) {
alert (e.message);
}
}
I am getting error :
"Automation server can not create object" on the line where I am creating ActiveXObject instance.
I understand that it's considered very bad to access hard-drive data using javascript but I just need it.
I am using IE8 , Greasemonkey4IE to run my javascript.
Thank you,
Mohit
******************************
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\source.txt","C:\\target.txt", 1);
}
I've put the above code inside a simple HTML page and it worked perfect.
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
You can find the similar code on above mentioned location.
I modified it a bit, tough.
But when I am trying to run it through GreaseMonkey4IE it simply spitting the same error I specified earlier.
I did it guys, but thanks a lot for your quick and helpful replies.
All I did is :
Go to Tools > Internet options > Security > Custom Level
Under the ActiveX controls and plug-ins, select Enable for Initializing and Script ActiveX controls not marked as safe.
Using native JavaScript, no, it is not generally possible to access a local file. Using plugins and extensions like ActiveX, Flash, or Java you can get around this rule, generally with some difficulty.
For some browser and OS specific exceptions to this general rule, you might want to have a look here:
Local file access with javascript
Note that as of late 2012, the FileReader API has been supported in all major browsers and provides a native JavaScript mechanism for accessing local files that the user nominates (via an input element or by dropping them into the browser).
This still cannot be used to access an arbitrary file by name/path as in the examples in the original question.
HTML5 File API has multiple ways to access local files.
window.requestFileSystem allows you to request access to the filesystem. Browser support is very poor on this (Chrome only).
FileReader is the HTML5 FileReader API that allows you to programatically read files that users select through a <input type='file' /> Browser support is better on this.
You should use fallbacks like flash and POST to a server for full file access.
Generally reading arbitary files is considered "cheating the browser" so I you'll either have to use secure HTML5, ActiveX or Flash. All 3 of those require user permissions.
After some research I have found:
var fso = new ActiveXObject("Scripting.FileSystemObject");
//This line will create a xml file on local disk, C drive
fh = fso.CreateTextFile( "C:\\fileName.xml", true);
fh.WriteLine("this is going to be written in fileName.xml");
This is how we can do it.There are other methods also.
Accessing local file system is very bad thing to do but yes we can do it.
Automation server can not create object
To get rid of this error go to Tools → Internet Options → Security → select Internet icon → click Custom level → select Enable for Initialize and script ActiveX controls not marked as safe for scripting.
I have not tested this on any other berowser except IE8, but I am sure it will work.
So - I've been using this method of file uploading for a bit, but it seems that Google Gears has poor support for the newer browsers that implement the HTML5 specs. I've heard the word deprecated floating around a few channels, so I'm looking for a replacement that can accomplish the following tasks, and support the new browsers. I can always fall back to gears / standard file POST's but these following items make my process much simpler:
Users MUST to be able to select multiple files for uploading in the dialog.
I MUST be able to receive status updates on the transmission of a file. (progress bars)
I would like to be able to use PUT requests instead of POST
I would like to be able to easily attach these events to existing HTML elements using JavaScript. I.E. the File Selection should be triggered on a <button> click.
I would like to be able to control response/request parameters easily using JavaScript.
I'm not sure if the new HTML5 browsers have support for the desktop/request objects gears uses, or if there is a flash uploader that has these features that I am missing in my google searches.
An example of uploading code using gears:
// select some files:
var desktop = google.gears.factory.create('beta.desktop');
desktop.openFiles(selectFilesCallback);
function selectFilesCallback(files) {
$.each(files,function(k,file) {
// this code actually goes through a queue, and creates some status bars
// but it is unimportant to show here...
sendFile(file);
});
}
function sendFile(file) {
google.gears.factory.create('beta.httprequest');
request.open('PUT', upl.url);
request.setRequestHeader('filename', file.name);
request.upload.onprogress = function(e) {
// gives me % status updates... allows e.loaded/e.total
};
request.onreadystatechange = function() {
if (request.readyState == 4) {
// completed the upload!
}
};
request.send(file.blob);
return request;
}
Edit: apparently flash isn't capable of using PUT requests, so I have changed it to a "like" instead of a "must".
(Spawned from a comment on the original question, per askers's suggestion.)
Plupload is one of the newest kids on the block and it uses the best method available (HTML 5, Flash, Gears, Silverlight): http://plupload.com/
I have previously used flash based ones such as http://www.webresourcesdepot.com/open-source-flash-uploader-multi-bit-shift/. They work ok and being only dependent on flash should work on most computers. I haven't found a reliable way of doing it with js alone but flash could be controlled with js - especially if you write your own.
hope this helps.