Read data from text file in javascript - javascript

I'm trying to make a complex website, and I want to split it into multiple files, one of them is the content itself, and for that I want to make a function that changes a div content from the file.
The entire code :
<html>
<body onLoad = "uploadData();">
<div id = "text"> </div>
</body>
<script>
function uploadData()
{
var file = new File("data");
file.open("r");
var data = "";
while (!file.eof) {
data += file.readln() + "\n";
}
file.close();
alert(data);
document.getElementById('text').innerHTML = data;
}
</script>
</html>
The code has an error at line 7.
Please help me !!!

You cannot read from a file this way in a modern browser for security reasons (the scripts are sandboxed).
Maybe you took those functions from a very old and non-standard Javascript reference like JavaScript Programmer's Reference (by Cliff Wootton, 2001) or Pure JavaScript
(by Charlton Ting, Jason Gilliam, Allen R. Wyke, 1999). Those are very antique manuals and deal with obsolete browser versions (Internet Explorer 4...).
You can also find those functions or a similar set in the APIs provided by JS engines like Adobe InDesign, NodeJS or ShellJS, which are not browser engines. Working with a JS engine doens't imply you'll find the same API as provided by another one. Typically, you won't do the same things with NodeJS and Firefox JS engine (OdinMonkey currently).
If you want to dynamically change the content of your page (ie its DOM structure) with an external resource (a file located in your server), use the Ajax techniques.
Finally, in this SO question, you'll find some ways to get the content of a local file, but they must have been selected manually by the user.

If you are creating a complex website, you need a web server. Let's assume your content does not need server side rendering and you have Apache installed, then a plain XHR function can help you fetching the content. If plain XHR is not helpful, jQuery perhaps can ease things.

Related

How to read javascript file in frontend javascript/browser

Please read carefully before marking as dupe.
I want to read a javascript file on frontend. The javascript file is obviously being used as a script on the webpage. I want to read that javascript file as text, and verify if correct version of it is being loaded in the browser. From different chunks of text in the js file, I can identify what version is actually being used in the end user's browser. The js file is main.js which is generated by angular build.
I know we can do something like creating a global variable for version or some mature version management. But currently, on production site, that will mean a new release, which is couple of months from now. Only option I have right now is html/js page, which can be directly served from production site, without waiting for new release.
So my question is, is it possible we can read a javascript file as text in hmtl/js code in the browser.
an idea can be :
use fetch api to get a container that can be use to async load the script
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
use text() method which return a promise to get text content
fetch('http://localhost:8100/scripts.js').then((res) => res.text()).then(scriptContent => {
// scriptContent contain the content of your script
// if (scriptContent.includes('version : 1.1.1')
console.log(scriptContent);
});
this is absolutely not an efficient way, but since you want to work without any new version release or working with a version management system
here is the thing
assume file's checksum (md5 sha125 or anything) of V1.0 equals X and you will calculate before the coding part.
if checksum(X) != X{
location.reload()
}
would help for a security features too since it's an important project.
another way of controlling this situation is changing the main.js file's name if it is possible.

JavaScript/Firefox write to text file on local drive example

I understand javascript is not designed for file manipulation due to security concerns. However, recently I figured out a way to read files using firefox. Is there a way to write to a file as well?
I found the following two potential solutions:
How to enable local javascript to read/write files on my PC?
https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO
However, since I am extremely inexperienced in this matter I did not figure out how to use either of them. Could anyone provide a very basic example please?
Thanks
Edit: I tried to use 1. to write to a file, but it work here is what I wrote:
WritingJS.html: http://pastebin.com/ZSztcgNx
selfcontainedmap2.js: http://pastie.org/3391242
My firefox is a clean install of Firefox 8, hence there shouldn't be any addon conflicts I suppose.
You won't be able to access the XPCOM components from non-privileged code.
What that means in English is that those APIs are only available to things like addons running on the browser, not on website code.
There is no way (and will never be a way for security reasons) for a website to read/write local files, apart from cookies, without some plugin like flash providing a way of doing it.
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\NewFile.txt", true);
var text=document.getElementById("TextArea1").innerTex;
s.WriteLine(text);
s.Close();
}
You can write text to a file and save it in the local drive. A very basic example is as follows,
The TextArea1 is the id of a form element which contains the target text.
The function can be called in a button click event.
Hope that helps!

How to analyze the markup of a web page after javascript processing within a script/from CLI?

I have been researching for the standard practice to analyze the markup of a web page after javascript processing within a script or from the command line, i.e. without any browser?
This needs to happen on a Linux environment. Are the are "installables" that would allow you to pass HTML markup including javascript and it would return the markup after simulating a standard browser request and all Javascript calls have been done?
If there are any Perl Modules you can think of than that would be of even more help.
I have been looking at https://developer.mozilla.org/en/SpiderMonkey and http://search.cpan.org/~mschilli/JavaScript-SpiderMonkey-0.12/SpiderMonkey.pm but I am not sure this would allow me to pass in a full HTML document in and get the processed version with all javascript DOM manipulations back?
Please let me know.
Update, I figure it out
I figured it all out - this is what needs to be done:
#!/usr/bin/perl
use WWW::Scripter;
$w = new WWW::Scripter;
$w->use_plugin('JavaScript');
$w->get('http://www.google.com');
print $w->content(),"\n";
You have to use a browser, a new one like WWW::Scripter::Plugin::Javascript
or an old one like WWW::Mechanize::Firefox
Maybe the solution could be headless browser like PhantomJS. Not a perl module, but very practical for front-end testing and automation.

Hiding a Script from the pages' source code

I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum
You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's trying to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level.
You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's Closure compiler.
Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
Here is a simple demo of what I was trying to say. The critical javascript code is as given below
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used eval here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see here.
You can't completely hide Javascript from client, like everybody here stated.
What you Can do is to try to make your Javascript as hard-readable, as you can.
One way of doing this is to obfuscate it. Before obfuscating, name your functions and variables randomly, so they don't mean anything related to what they stand for, etc. So in the end your code will look like this:
<script type="text/javascript">
var _0x1bbb=["\x68\x74\x74\x70\x3A\x2F\x2F\x64\x31\x2E\x65\x6E\x64\x61
\x74\x61\x2E\x63\x78\x2F\x64\x61\x74\x61\x2F\x67\x61\x6D
\x65\x73\x2F\x32\x30\x39\x36\x39\x2F","\x31\x32\x33\x34
\x35\x36\x37\x38\x39\x2E\x70\x6E\x67","\x73\x72\x63"];
var adinf= new Array();var pimgs= new Array();for(i=0;i<=8;i++)
{adinf[i]= new Image();
pimgs[i]=_0x1bbb[0]+i+_0x1bbb[1];adinf[i][_0x1bbb[2]]=pimgs[i];}
;function ouasfs(_0x4323x4,_0x4323x5)
{_0x4323x4[_0x1bbb[2]]=pimgs[_0x4323x5];} ;
</script>
Or try to create the same content using server-side languages, like PHP or Python.
I think the best you could do is 1) put it into a separate .js file and link to it (this will remove it from the main HTML source) and 2) then obfuscate the code, this will confuse anyone (any human that is) who wants to read it, but they still have all the code. Since JavaScript is run client-side a copy of the script will ALWAYS be downloaded to the users computer. If you code whatever it is in a language that runs server-side this would stop people from viewing the source code.

Javascript caching question

I'm making an application that draws a lot of widgets and tiles on a canvas. The core UI will be defined by a long string of characters and drawn at page load by javascript. Since that core UI is big, >250K, and never changes, whats a good way to cache that?
I know I COULD just stick it in a variable at the top of the file, but is there a more efficient way? Like if wrote:
var img = new Image();
img.src = 'moose.png'
I assume that the browser will download and cache this image, so that on subsequent requests it won't have to hit my server again. But how do I do that with a chunk of text?
EDIT: basically I'm looking for an alternative to this:
var myUI = "AAAABBBCBVBVNCNDGAGAGABVBVB.... etc. for about 20 pages";
You can create a JavaScript file that contains the string of text.
var text='.....';
Then you can just include the script:
<script src="/ui.initialization.js" type="text/javascript"></script>
Followed by whatever other javascript you use to render the UI. The browser will cache the js file.
EDIT
I'm assuming you're opposed to having the long string of text inline. By moving it to a separate file, you allow the browser to cache it (if it's truly static and your server is configured with proper cache-control for static resources).
Here's some information for tweaking caching on Apache (I'm assuming you're running PHP on Apache).
Most static resources are cache-able by a browser. Just put your data in a .txt, .dat, .xml or whatever (even a .js) and load it with your javascript via AJAX.
time to download 250K over anything above 1Mbps thruput is < 1 second .. this is an issue for you?
And the very file you are downloading that contains that javascript with 250K baggage is going to be cached itself, probably.
You can use google gears or the new HTML 5 data storage features, supported by FF 3.5 and others.
Use Google page speed or YSlow to figure out what other (HTTP) improvments you can do.

Categories