There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.)
So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too.
Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages":
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : "../../../secret_code.js",
dataType: "text",
success : function (data) {
$("#ajaxcontent").html(data);
}
});
});
</script>
1) Why can't I load a file from the root directory with ajax or load method?
2) Is there another way around?
PS: I'm putting the file in the root directory so people can't access it directly from their browsers...
1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers
2) try /secret_code instead of ../../../secret_code.js
What is your system setup? Are you using a CMS?
Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/
If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you.
Navigate to the URL, not the directory. Like
$.ajax({
url : "http://domain.com/js/secret_code.js",
..
Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer
Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
Try jQuery's $.getScript() method for loading external
Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar!
Security first
You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible.
You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js
If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles.
If you want to keep it secret, don't let it get to the browser.
Related
I am trying to read a text file that is in the same directory as my html file using javascript so that I might include the contents of the text file in my html file.
Here is the code I have to test the fopen and fread functions
<html>
<head>
</head>
<body>
<script>
fh = fopen('my.txt', 0); // Open the file for reading.
if(fh!=-1) // Check if the file has been successfully opened.
{
length = flength(fh); // Get the length of the file.
str = fread(fh, length); // Read in the entire file.
fclose(fh); // Close the file.
// Display the contents of the file.
write(str);
}
</script>
</body>
</html>
I've tried replacing the 'write' with document.write and still nothing.
Here are some websites that had this code as an example:
http://answers.yahoo.com/question/index?qid=20130519190823AA2lQ1W
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
Any help at all would be much appreciated.
Thank you!
Javascript has no filesystem access. As it is mentioned in the second link you posted,
you will need to install special plugins in order to give JS file system access.
I don't think it is the right way to accomplish whatever you are trying to do.
In order to access client's filesystem, the popular way I've seen is using Flash or Java applet or Microsoft Silverlight for that matter.
For accessing your server filesystem, you will need to run a web server which has proper permissions to access the filesystem. Then, you can make AJAX calls to the web server, which in turn will fetch the file for you.
As Apoorv said, JavaScript has no filesystem access. But I think it is important to consider why that is. Or rather, ask yourself, would you go to a website that could access files on your machine?
Functions like fopen is not defined in web browsers. You cannot access file system from javascript. Either have to do something like this: Question
or load your files with ajax
Either way you cannot load file's from viewer's computer, only from your server.
Again either way trying to load from a different server will also result in cross origin related limitations.
I have a .csv file that I wish to load that contains information that the .HTML page will format itself with. I'm not sure how to do this however,
Here's a simple image of the files: http://i.imgur.com/GHfrgff.png
I have looked into HTML5's FileReader and it seems like it will get the job done but it seems to require usage of input forms. I just want to load the file and be able to access the text inside and manipulate it as I see fit.
This post mentions AJAX, however the thing is that this webpage will only ever be deployed locally, so it's a bit iffy.
How is this usually done?
Since your web page and data file are in the same directory you can use AJAX to read the data file. However I note from the icons in your image that you are using Chrome. By default Chrome prevents just that feature and reports an access violation. To allow the data file to be read you must have invoked Chrome with a command line option --allow-file-access-from-files.
An alternative, which may work for you, is to use drag the file and drop into onto your web page. Refer to your preferred DOM reference for "drag and drop files".
You can totally make an ajax request to a local file, and get its content back.
If you are using jQuery, take a look at the $.get() function that will return the content of your file in a variable. You just to pass the path of your file in parameter, as you would do for querying a "normal" URL.
You cannot make cross domain ajax requests for security purposes. That's the whole point of having apis. However you can make an api out of the $.get request URL.
The solution is to use YQL (Yahoo Query Language) which is a pretty nifty tool for making api calls out of virtually any website. So then you can easily read the contents of the file and use it.
You might want to look at the official documentation and the YQL Console
I also wrote a blog post specifially for using YQL for cross domain ajax requests. Hope it helps
You can try AJAX (if you do not need asynchronous processing set "async" to false. This version below ran in any browser I tried when employed via a local web server (the address contains "localhost") and the text file was indeed in the UTF-8-format. If you want to start the page via the file system (the address starts with "file"), then Chrome (and likely Safari, too, but not Firefox) generates the "Origin null is not allowed by Access-Control-Allow-Origin."-error mentioned above. See the discussion here.
$.ajax({
async: false,
type: "GET",
url: "./testcsv.csv",
dataType: "text",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
//parse the file content here
}
});
The idea to use script-files which contain the settings as variables mentioned by Phrogz might be a viable option in your scenario, though. I was using files in the "Ini"-format to be changed by users.
I'm developing a small application with HTML, CSS, Javascript, JQuery and JQTouch.
This is a LOCAL application. I've an index.html with some div's. When I click on a link in this file, I want to load HTML code of page1.html (same folder) and insert into a div of index.html the tag that I want of page1.html.
Example: Inject the content of (page1.html) into (index.html).
I try: http://api.jquery.com/load/
$('#loadContent').load('page1.html #test');
And the content of loadContent doesn't change. I include JQuery script into index.html...
I try http://api.jquery.com/html/ too, but I think it connect to the server.
Any idea? Thanks!
Make sure you're calling it after loadContent has been created. The following will run your load code when the document is ready to be written to.
$(function() {
$('#loadContent').load('page1.html #test');
});
Or you could run a local server. If you have python you can go to your directory with the files and run python -m SimpleHTTPServer for python 2.7 or python -m http.server for python 3.x
Most browsers will, by default, block this on a local file system as a security precaution. Have you tried it on a remote server?
I dont know much on jQuery. But still, you can do this, by loading the page1.html to a hidden iframe, then get the document.body.innerHTML of this page, and then append that node to the div you need. Its only HTML DOM in JavaScript.
But performance base, loading an iframe is always a costly one. This would do your job. However there may be many solutions in jQuery or other libraries, Sorry i don't know much on it.
It sounds like the problem is that the jQuery library isn't loading when you're running on localhost, or the AJAX request is failing for the same reason. This is due to protection built into the browser to prevent cross-site scripting.
See this "additional note" from the documentation for load:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
If you use any AJAX, you'll have to run this on a local web server. In which case you should just run this page from your local webserver rather than from the filesystem. Then you won't need any workarounds.
If you're on Windows, you could use UniServer.
If you aren't going to use any AJAX whatsoever (aren't using load), then you could write your code so that it falls back to a local version of jQuery if the remote version didn't load.
Here's an example of how, grabbed from this page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="/Scripts/lib/jquery/jquery-1.4.4.min.js"></script>'))</script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>!window.jQuery.validator && document.write('<script src="/Scripts/lib/jquery/jquery.validate.min.js"></script>')</script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"></script>
<script>!window.jQuery.validator.unobtrusive && document.write('<script src="/Scripts/lib/jquery/jquery.validate.unobtrusive.min.js"></script>')</script>
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.
I'm building a local html file to show dynamically some data from an XML file and by using Chrome's Inspector I figured my XML file is not being parsed because it is "not hosted on a webserver"
XMLHttpRequest cannot load data.xml. Cross origin requests are only supported for HTTP.
I know that there are a few flags I could pass to Chrome/web browser to workaround this limitation but I'm looking into some alternative method. I will probably have to distribute this files to a few people and teaching them how to pass flags to the browser is not an option for me. Hosting them on a web server is not an option either.
Thanks a lot in advance.
No ghost unless you set up a local server or host the XML file locally. Ajax has to follow the same origin policy.
If you're willing to use a library you can use jQuery's AJAX method to perform a cross-domain request (i'm not entirely certain that jQuery will support what you're trying to do). JSONP works, but you have XML data...
You could try loading it in a script tag anyway and see if you can get the innerHTML value without breaking the script; once you're done getting the text from it, remove the script from the page. You may be able to get at the data before the browser tries to parse the script by attaching onload and onreadystatechange events to the script element.
var s = document.createElement('script');
s.src = '/path/to/file.xml';
s.onload = s.onreadystatechange = getData;
function getData(e)
{
//get the text out of the script element
//remove the event handler from the script element
//remove the script from the page
}
document.getElementsByTagName('body')[0].appendChild(s);
I didn't test it, but it might work.
How about setting up a local webserver? XAMPP should be easy to install even for novice. Just tell them to put your files in the htdocs folder, run xampp and start the apache server.
Unless there's a compelling reason to have a separate html and xml file, you could just put the data directly in the html file.
I'm afraid if chrome only provides options that you don't like to apply, your application and chrome will not come together. Access via iframe & object does'nt work too, load()-method of createDocument is not supported by chrome(if it does I guess you got the same error).
Whatever you try will be a sideway to pass chrome's restrictions, what cannot be good, because I think they have good reasons to setup these restrictions.