I want to write a function in javascript which creates a file and write some content to it, iam working with firefox, can anybody help me in this case.
Thanks...
You can write files in JavaScript in Firefox, but you have to use an XPCOM object (internal browser API). This is not allowed for JavaScript loaded from a web page, and it is intended to be used by JavaScript running inside a Firefox add-on (with high level of privileges).
There is a way for unprivileged (web page) JavaScript to request more privileges and if the user grants it (there will be a pop up dialog asking for permission), the web page code would be able to write to a file.
But before you read further, a warning:
This is not standard JavaScript and I would not recommend this approach unless you are developing a very specific application, that will be used in a very specific way (like for example, http://www.tiddlywiki.com/ a client-side JavaScript-HTML only wiki).
Requesting XPCOM privileges on a website is a bad practice! It's basicly equivalent to running an .exe you just downloaded from a site. You are asking a user to grant full access to their computer (read, write, execute) with the identity of the user running Firefox.
Request permission to use XPCOM (this will prompt the user for confirmation, no way to avoid it):
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
Then, write to a file using an XPCOM object (example code from Mozilla Developer Network):
1. // file is nsIFile, data is a string
2. var foStream = Components.classes["#mozilla.org/network/file-output-stream;1"].
3. createInstance(Components.interfaces.nsIFileOutputStream);
4.
5. // use 0x02 | 0x10 to open file for appending.
6. foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0);
7. // write, create, truncate
8. // In a c file operation, we have no need to set file mode with or operation,
9. // directly using "r" or "w" usually.
10.
11. // if you are sure there will never ever be any non-ascii text in data you can
12. // also call foStream.writeData directly
13. var converter = Components.classes["#mozilla.org/intl/converter-output-stream;1"].
14. createInstance(Components.interfaces.nsIConverterOutputStream);
15. converter.init(foStream, "UTF-8", 0, 0);
16. converter.writeString(data);
17. converter.close(); // this closes foStream
You can find more information about I/O in Firefox using XPCOM here: https://developer.mozilla.org/en-US/docs/Code_snippets/File_I_O
Javascript from websites cannot access the local file system.
If you like to store data either store it on the server or in a cookie.
writing to the file system directly from a browser is prohibited for security reasons. With html5 however it'll be possible to have offline storage support. Take a look here.
Grz, Kris.
Javascript executes in a client-side context.
http://www.tek-tips.com/viewthread.cfm?qid=1171273&page=1
There will be an API for this.. File Writer API. The early specification is here:
http://www.w3.org/TR/file-writer-api/
It is not implemented in any browser yet.
Update: It seems there already exists an implementation. Check out http://caniuse.com/filesystem and http://www.html5rocks.com/en/tutorials/file/filesystem/
While everyone who's responded that javascript does not have the ability to write files on a remote server are correct, and this is true for security reasons, what you want to accomplish may still be possible.
For example, if you wanted to make it possible to create a file on your website with the use of javascript, you can do so with some server side scripting language and and AJAX call.
Example:
You have a file on your server called update_last_access.php which will create a file which stores the last time the file was accessed in some arbitrary file.
If you then had your javascript function make an AJAX call out to that script, for instance, in jquery
$.get("update_last_access.php")
Then this would execute the server side script and write to the file.
Before any more help can be provided for you, you're going to have to clarify what you're trying to do.
You can read files from the filesystem in JavaScript with Firefox 3.6 - see my EPUB reader proof of concept, for example.
You can't write files directly from JavaScript, though. You have to go via a server.
Mozilla is planning to include FileSaver to Gecko 9:
https://bugzilla.mozilla.org/show_bug.cgi?id=557540
Related
Currently my Office is running a AHK script to pull environment variables. These Env Variables are then used as a specific outputted data when closing tickets as my Office has a ticket closing environment. This works for the time being however I am looking into automating this process and starting off just trying to auto close the tickets when a specific key is pressed. I have been able to perform this task but I have to basically have static variables in the TamperMonkey script for each user. Everyone using this ticket site has the specific environment variables already due to the AHK script and want to try and implement this into the Tampermonkey script without having to change the site completely.
I have locally hosted the site and used Node to do this and I am successful in doing this but it does not work on the Tampermonkey route. I have been using process.env.ENV_VARIABLE on the node side but I am trying to refrain from completely implementing this on the site itself. I have added some basic variable examples in a Autohotkey Script already being used.
GetGreeting() {
global greeting
return greeting
}
GetSalutation() {
global salutation
return salutation
}
GetUserName() {
Envget, e_Ticketname, Ticketuser
return e_Ticketname
}
When a specific Key is pressed it should write the specific message and include said specific Env Variables. Currently I don't think I have it where Tampermonkey can actually understand the Environment Variables as it keeps giving a undefined error. Any Ideas.
So upon further investigation it does not appear to be a way to interact with the OS inside the browser. I will be looking into another way to do what I am looking for. Thank you!
You are able to access and run local files as JavaScript code in Tampermonkey using \\ #require
So if you're able to have a local file with the content in this format:
variables = {
var1: "hello there"
}
Then in the script, add this line and add the path to the file.
// #require file://Path\to\file
Since all the file has is an assignment to a variable, then you can access that in the script
console.log(variables.var1) // logs "hello there"
For this you need to give the extension access to file URLs:
go to chrome://extensions
Tampermonkey > Details
Allow access to file URLs
You'll still need a way to generate the file in that format in the user machine though, either manually, or some code running locally.
A way to generate the file, could be using Node locally, but if you're running that locally, at that point another way to get local data is to serve it using a simple http server (like Node server), then you could make a request from Tampermonkey using fetch or GM_xmlhttpRequest
As a side note, a hack I use to run code locally triggered with Tampermonkey, is to use the localexplorer extension. The extension allows you to open files and folder from the browser using "localexplorer://" urls, so then with javascript you can do window.open(local_url) and it will run or open that file/folder. The file can also be a .bat file, and you can run anything from it (including Node code).
There are some security considerations for using this though if you're worried other websites might be able to open files in your system. but the extension prompts you every time you try to open something with localexplorer
If you're still interested on this, a way I use for it to work without the prompt with less risk is this:
The prompt also lets you click the checkbox of Always open links of this type in the associated app for each domain. So then what you can do, is have a specific domain you choose for this, to always use that domain to open localexplorer links, and use a format of your choosing, like secretdomain.com/?C:\\path\\to\\file, and grant access to always open the links on that domain. Then use Tampermonkey to run some code on that domain so that when it detects that specific url format, to redirect the page to a localexplorer url, like this
location.href.replace(/htt.*:\/\/secretdomain.com\/\?/,'localexplorer:')
i have a c++ file which reads values from a sensor and I want to display those values on a website dynamically. So Im looking for a way to pass these values(integers) from my cpp file to an javascript which displays them on the site.
My first, simple try was to write the values into a js file as variables every second from my cpp script. The Js then uses this file as a source and displays its variables on the site:
cpp:
fprintf(file, "var mx=%d, my=%d, mz=%d, ax=%d, ay=%d, az=%d, gx=%d, gy=%d, gz=%d;\n",
imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], // M = Magnetometer
imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], // A = Accelerometer
imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] // G = Gyroscope
);
html/js:
<script src="./imu.js" type="text/javascript"></script>
The Problem now is of course, that I need to refresh the page all the time, because the imu.js file is cached by the website.
I'd rather have a way to directly pass to integers from the cpp file to the js script. I read something about json or Googles V8 script. But I'd like to hear your suggestions first.
By the way, Im running this on a raspi, if this is important.
Thanks for your help
EDIT:
I'm goning to try it with a mysql database, in which my cpp file writes the data from the sensor with Connector/c++ from http://dev.mysql.com/doc/connector-cpp/en/ and my website reads them.
You could compile your C++ code into a Node.js plugin, you can then register a JavaScript function with your plugin which the C++ calls when it updates the value. That way you can pass values directly from C++ into Javascript in a managed and controlled way.
Node.js has the added benefit of being able to host your webpage and do all the Websocket and HTTP stuff that can be a pain in C++.
You do not have to refresh if your script is smart about how to access the data file! In case you do have a webserver at hand: Take care that your data file is accessible by your webserver and then let your script request the file via ajax (link to w3schools)
I'm doing something similar on a BeagleBone Black. With websocketd you can turn pretty much any program into a websocket endpoint and then send data via stdin and stdout commands. This would be a particularly good solution for you since websockets are designed to handle information that's constantly changing.
I have php made website. It runs on windows machine. I have a javascript that i have tested that gets me the adobe version used by clients. The problem is that by running the code I'm able to retrieve the Adobe Reader version but cannot saved the output to a file on my server end.
Here is the Javascript code. I took this code from sister stackexchange website.
http://jsfiddle.net/EGbY5/3/
What is the best way to save this information from js? Should i use js or any other scripting? I read this from google that you cannot use js to save files on server? If this is true is there any other way.
I would suggest using AJAX (or a form, if you want the user to explicitly know this is happening) to send a request to your server side code detailing the information you have collected with the script.
The advantage of AJAX is that you can do all of this without the user being explicitly aware of it. The disadvantage is that you rely on their browser supporting Javascript, but since you are already collecting information using Javascript this problem is mute.
Ajax'll do it.
JavaScript source:
var adobeVersion = CheckAdobeVersion();
$.post("script.php", {version: adobeVersion}, function(){});
PHP source:
<?php
$version = $_POST['version'];
write all text to a file("my file.txt") // Pseudo code...
?>
I have an input type="file" button. After I choose a file, I have to read the contents of the file using javascript. Is it possible to read/get contents of a chosen file using javascript or ajax?
You are all wrong in a way. It is possible. With the new File API you can read files before submitting them to the server. It is not available in all browsers yet though.
Check this example. Try to open a text file for example.
http://development.zeta-two.com/stable/file-api/file.html
Edit: Even though the question states "uploaded file" I interpret it as, "a file to be uploaded". Otherwise it doesn't make sense at all.
With AJAX its possible to read uploaded file but with pure javascript its not possible because javascript works on client side not on sever side.
if you are going to use jquery than Ajax call may be like this
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Reading files client side is hard:
How to read and write into file using JavaScript
Read a local file
Local file access with javascript
Unless you are trying to do it with local javascript:
Access Local Files with Local Javascript
Or server side javascript:
http://en.wikipedia.org/wiki/Server-side_JavaScript
Alternatively you can force your user to install an ActiveX object:
http://4umi.com/web/javascript/fileread.php
you cant do it using javascript directly. You can post the file to the server an then use ajax to retrieve the content.
Javascript is designed not to have access to the computer it is running on. This is so that rogue javascript can't read the user's harddrive.
You could look into using iframes though.
It is not possible to do it in java script. See Local file access with javascript
I agree with DoXicK above. You can post the file first on server and then you can use Ajax to read it.
That is not entirely impossible
A browser's usually runs Javascript(JavaScript Engine) in a sandboxed environment.
So you can use Windows Scripting Host or Internet Explorer in a trusted environment and use the FileSystemObject
or use
Or upload a file to your server and use the XMLHttpRequest object.(in other words - Ajax)
For IE use the FileSystemObject (which is found on all Windows systems).
For Firefox:
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home");
See https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
To see these methods and others in use, look at TiddlyWiki app to see how it does it across all major browsers.
If this has been asked before, I apologize but this is kinda of a hard question to search for. This is the first time I have come across this in all my years of web development, so I'm pretty curious.
I am editing some HTML files for a website, and I have noticed that in the src attribute of the script tags that the previous author appended a question mark followed by data.
Ex: <script src="./js/somefile.js?version=3.2"></script>
I know that this is used in some languages for value passing in GET request, such as PHP, but as I far as I ever knew, this wasn't done in javascript - at least in calling a javascript file. Does anyone know what this does, if anything?
EDIT: Wow, a lot of responses. Thanks one and all. And since a lot of people are saying similar things, I will post an global update instead of commenting everyone.
In this case the javascript files are static, hence my curiosity. I have also opened them up and did not see anything attempt to access variables on file load. I've never thought about caching or plain version control, both which seam more likely in this circumstance.
I believe what the author was doing was ensuring that if he creates version 3.3 of his script he can change the version= in the url of the script to ensure that users download the new file instead of running off of the old script cached in their browser.
So in this case it is part of the caching strategy.
My guess is it's so if he publishes a new version of the JavaScript file, he can bump the version in the HTML documents. This will not do anything server-side when requested, but it causes the browser to treat it as a different file, effectively forcing the browser to re-fetch the script and bypass the local cache of the file.
This way, you can set a really high cache time (like a week or a month!) but not sacrifice the ability to update scripts frequently if necessary.
What you have to remember is that this ./js/somefile.js?version=3.2 doesn't have to be a physical file. It can be a page which creates the file on the fly. So you could have it where the request says, "Hey give me version 3 of this js file," and the server side code creates it and writes it to the output stream.
The other option is to force the browser to not cache the file and pull down the new one when it makes the request. Since the URI changed, it will think the file is completely new.
A (well-configured) web server will send static files like JavaScript source code once and tell the web browser to cache that file locally for a certain period of time (could be a day, a week, a month, or longer). When the browser sees another request for that same file, it will just use that version instead of getting new code from the server.
If the URL changes -- for example by adding a query string -- then the browser suspects that its cached version is no good and gets a new one. As such, the ? helps developers say "Oops, I changed this file, make sure the browser gets a new copy."
In this case it's probably being used to ensure the source file isn't cached between versions.
Of course, it could also be used server side to generate the javascript file, without knowing what you have on the other end of the request, it's difficult to be definitive.
BTW, the ?... portion of the url is called the query string.
this is used to guarantee that the browser downloads a new version of the script when available. The version number in the url is incremented each time a new version is deployed so that the browser see it as a different file.
Just because the file extension is .js doesn't mean that the target is an actual .js file. They could set up their web server to pass the requested URL to a script (or literally have a script named somefile.js) and have that interpret the filename and version.
The query string has nothing to do with the javascript. Some server side code is hosting up a different version depending on that querystring it appears.
You should never assume anything about paths in a URL. The extension on a path in a URL doesn't really tell you anything. URLs can be completely dynamic and served by some server side code or can rewritten in web servers dynamically.
Now it is common to add a querystring to urls when loading javascript files to prevent client side caching. If the page updates and references a new version of the script then the page can bust through and cause the client to refresh it's script.