The following code, located inside of an HTML file, reads the contents of a local .txt file into a Javascript string variable:
<script>
window.onload=function(){
var allText;
readTextFile("/files/Textfile.txt");
function readTextFile(file)
// https://stackoverflow.com/a/14446538/8840617
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
}
}
</script>
The JavaScript code continues to parse this text to extract a specific substring from allText, and then finally this substring is shown to the user in the HTML.
The problem is that any visitor can find the text file's path by clicking "View Source" in their browser, and then they can navigate to the text file in their browser to see the file in full.
I do not want anyone to be able to see the complete contents of this text file.
So, is it possible to prevent visitors from viewing the .txt file, while still allowing my .html webpage to import the data from the .txt file as a string?
If it is not possible, how should I accomplish this effect, exactly?
No - that's an attempt at a security through obscurity model and not a very obscure one. You can't trust the client or hide information from it. If a script can see it, a malicious or inquisitive user can see it too.
The solution is to expose on your server what someone should be able to see and no more. If the content is private for specific users, you'll need to setup some kind of login and authentication when they request it.
I want to read a file that's saved in the same folder. Then I want to show its content in a div in index.html. The problem: when I used require("fs") it didn't work since it wasn't running server-side. I have been looking around and can't find a simple answer. I want to make my website a little dynamic, so here is the code that should fire upon a button click:
function videos() {
var body = *read a file("insertfilename")*;
console.log(body);
document.getElementById("body").innerHTML = body;
}
"body" in this case is just the id I gave the div.
!EDIT!
Now to explain it further. I want to use it as my main website. When I go onto there it should open an empty html file, which has a scriptfile as source. "onload" it should read a file , which is also already on the server, and put its content into a div inside of the body. If I click on a hotlink or a Button, it should read another file and put that content into that div instead. Maybe that gives a little clarification on what I am trying to do. I dont want to reload to open other sites of mine.
Seems like you need some basic file fetching since you are not using a server. Have you tried FileReader for javascript? It is a very simple and straightforward object. The example on the page seems similar to what you are trying to accomplish, except you want to fetch the file, not the user.
You can use AJAX. It stands for Asynchronous JavaScript And XML. You can send asynchronous requests to server with it. Just make sure that file that you are requesting is on the same domain as JS file.
function videos() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { //this will execute when you receive response from the server
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML = this.responseText;
console.log(this.responseText)
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
}
Here is W3schools tutorial if you want to learn more.
I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work
Which is the best method to make the browser use cached versions of js files (from the serverside)?
Have a look at Yahoo! tips: https://developer.yahoo.com/performance/rules.html#expires.
There are also tips by Google: https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
or in the .htaccess file
AddOutputFilter DEFLATE css js
ExpiresActive On
ExpiresByType application/x-javascript A2592000
I just finished my weekend project cached-webpgr.js
which uses the localStorage / web storage to cache JavaScript files. This approach is very fast. My small test showed
Loading jQuery from CDN: Chrome 268ms, FireFox: 200ms
Loading jQuery from localStorage: Chrome 47ms, FireFox 14ms
The code to achieve that is tiny, you can check it out at my Github project https://github.com/webpgr/cached-webpgr.js
Here is a full example how to use it.
The complete library:
function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};
Calling the library
requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
requireScript('examplejs', '0.0.3', 'example.js');
});
From PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
works for me.
As a developer you'll probably quickly run into the situation that you don't want files cached, in which case see Help with aggressive JavaScript caching
In your Apache .htaccess file:
#Create filter to match files you want to cache
<Files *.js>
Header add "Cache-Control" "max-age=604800"
</Files>
I wrote about it here also:
http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/
I am heavily tempted to close this as a duplicate; this question appears to be answered in many different ways all over the site:
will a script in html's script tag with extension php be cached?
When does browser automatically clear cache of external JavaScript file?
Help with aggressive JavaScript caching
How to control web page caching, across all browsers?
How can I make the browser see CSS and Javascript changes?
The best (and only) method is to set correct HTTP headers, specifically these ones: "Expires", "Last-Modified", and "Cache-Control". How to do it depends on the server software you use.
In Improving performance… look for "Optimization on server side" for general considerations and relevant links and for "Client-side cache" for the Apache-specific advice.
If you are a fan of nginx (or nginx in plain English) like I am, you can easily configure it too:
location /images {
...
expires 4h;
}
In the example above any file from /images/ will be cached on the client for 4 hours.
Now when you know right words to look for (HTTP headers "Expires", "Last-Modified", and "Cache-Control"), just peruse the documentation of the web server you use.
I have a simple system that is pure JavaScript. It checks for changes in a simple text file that is never cached. When you upload a new version this file is changed. Just put the following JS at the top of the page.
(function(url, storageName) {
var fromStorage = localStorage.getItem(storageName);
var fullUrl = url + "?rand=" + (Math.floor(Math.random() * 100000000));
getUrl(function(fromUrl) {
// first load
if (!fromStorage) {
localStorage.setItem(storageName, fromUrl);
return;
}
// old file
if (fromStorage === fromUrl) {
return;
}
// files updated
localStorage.setItem(storageName, fromUrl);
location.reload(true);
});
function getUrl(fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", fullUrl, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === XMLHttpRequest.DONE) {
if (xmlhttp.status === 200 || xmlhttp.status === 2) {
fn(xmlhttp.responseText);
}
else if (xmlhttp.status === 400) {
throw 'unable to load file for cache check ' + url;
}
else {
throw 'unable to load file for cache check ' + url;
}
}
};
}
;
})("version.txt", "version");
just replace the "version.txt" with your file that is always run and "version" with the name you want to use for your local storage.
I am new to javascript (mostly work on backend) but now I want to create a visualization and want to use javascript for it.
I have data saved in a file in format
id1 uid1 rating
id1 uid2 rating2
Just to get started, I want to read data from this file and display it on my browser?
Do I need to start server.. or can i do it just like that.
Any suggestions/directions will be appreciated.
THanks
you need to learn about ajax,and deal with browser differences. A way that would work on firefox and chrome would be :
<body>
<div id="log"></div>
<script type="text/javascript">
var request = new XMLHttpRequest();//depends on the browser , several ways to create the object
request.onreadystatechange = function(e){
if(request.readyState == 4 && request.status==200){
// do whatever you need with the data
document.getElementById("log").innerText = request.responseText;
}
}
// assuming the file is called data and is located on current-path-on-server/data
request.open("GET","data",true);
request.send();
</script>
</body>
more about it :
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started