Difference between Localhost and opening html file - javascript

What is the fundamental difference running a file using a server in localhost, and opening a file such as file:///Users/$user_name/$your_directory/index.html, assuming no backend is used, and it is only frontend and contains html/css/js
How does this also affect interactions with other server ie. ajax requests?
I am sorry if this is too broad, but I haven't found a solid answer to these underlying questions.

Fundamentally, assuming at some point you're going to host the result on an actual web server, the former matches the target environment while the latter doesn't. Browsers treat local files and files served from web servers (even localhost web servers) differently, although very similarly. One aspect of this is the encoding: When you retrieve a file from a web server, the process of determine what encoding the data is in is different from opening a local file.
How does this also affect interactions with other server ie. ajax requests?
This is one of the primary ways in which they're handled differently, and it even varies from browser to browser. A page loaded from a file:// URL has origin null from a Same Origin Policy standpoint. Some browsers (like Chrome) disallow Cross-Origin Resource Sharing entirely for origin null, even when the server you're trying to talk to has a wide-open CORS policy (*). Others (like Firefox) allow origin null to match the wildcard.
In general, for best results, ensure that your development environment matches your deployment environment in the important ways. That means doing your development using a web server process rather than local files. Most IDEs will happily provide that process for you; if not, Apache or Nginx aren't hard to install.

answer is simple,
if u don't have made active backend yet for "index.html" then it would not effect.e.g.-"localhost" and "index.html" will be same this time.
but when u start working with the backend,then most of the backend processes need an active server (need localhost).
e.g.-
1.
fetch('local.json')... //fetch json or any file would not work for local files.
2.
u may not ineract with mysql/django etc. databases.
means it cause errors in signup/login , store any image/video/docs at database etc.
so better is work in localhost, it's most easy way is :-
VScode(IDE) >> extenctions >> live server (just need to click a button to make
localhost and click again to stop localhost)
https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

It won't make any difference, I think.
But there is an exception when using Chrome! Sometimes I have seen if a html file is added with some CDN link, then it doesn't loaded into html specifically in Chrome but if you try the same file in Firefox or Internet Explorer, it works.
I have faced this problem and hence I always put it under local IIS default website.

Related

Can a file served by http (localhost or remote) be accessed from a local file opened through file:// protocol? And vice versa? How to implement this?

I've got several html files (TiddlyWiki Classic instances) which are stored on a USB-stick (and for it to remain removable, I open them through the file:// protocol). I use Ajax (via SharedTiddlersPlugin, but that's not that improtant) to load contents of some of them into others of them and that works nicely.
I've also set up several TWs using localhost (WAMP # Windows 10 and a simple saving server called MicroTiddlyServer, the latest version can be found here). But "including" (via Ajax request) from localhost to file and from file to localhost does't work.
So, the question is which ways of including (loading content of an html using JavaScript) is possible:
from file to localhost? Meaning that I open a TW at localhost and get contents of a file on my USB-stick (looks like a big security issue, so it's more likely that this is forbidden, at least using Ajax, but may be there's some workaround),
from localhost to file? (my guess is it's possible via CORS, but adding Header set Access-Control-Allow-Origin "*" to <Directory ...> of Apache's httpd.conf prevents my server (WAMP pack # Windows 10) from working and putting .htaccess file with the Header set Access-Control-Allow-Origin "*" content into the TW directory causes Internal Server Error \n The server encountered an internal error or misconfiguration and was unable to complete your request.)
from remote server to file? (I guess this shouldn't differ much from 2. aside that I usually can't configure the server as I'm not an admin; but as I'd like to use TW as an RSS aggregator, let me include this here, too; this also would help including from and TWs on my smartphone which can be served from there using a PHP server; including to TWs on the smartphone requires localhost->remote server, though, which seems forbidden, too)
I really need some working examples (not necessarily with TW, just with html files) as I'm kinda lost in all those CORS questions and tutorials (the latter being about http, not file protocol). Actually, any working solution (not necessarily via Ajax) will do if:
my USB-stick remains removable at any time except for saving moment
the server-side part can be done at Android as well (PHP is good, Python should do as well, although I haven't tested it yet) and server config is described clearly (well, this happened to be not clear enough in my case)
including remains async
In fact, there's quite a number of ways described for servers, but working with file:// is somewhat different (there's no server to configure!).
The main goal of this question is to understand whether I have to create a server which will serve TWs on USB-stick once it's inserted or I can achieve all 3 goals in a "mostly client-side" way (opening TWs through file protocol). But also I hope that working examples will be helpful for others since this topic seems somewhat poorly documented.
For evident security reason this behaviour is not allowed.
from file to localhost? Meaning that I open a TW at localhost and get contents of a file on my USB-stick (looks like a big security issue, so it's more likely that this is forbidden, at least using Ajax, but may be there's some workaround),
It is not allowed as you cannot use Access-Control-Allow-Origin in an html meta tag.
from localhost to file?
from remote server to file?
Actually, that's the same, there's a web-server, so it's the same mechanism. And as no server will respond with the Access-Control-Allow-Origin header, you cannot access file:// url.
yes accessing file from a server is surely a security issue, but why accessing a server from a file-served html is an issue?
If you could do that, you could send your entire hard drive anywhere on the web just by double clicking on a file.html in your file explorer...
The only way to access your content is to serve it, sorry.

Exclusion of the URL scheme in front of a URL

Recently I've seen these kinds of URLs in CDN documents:
//cloudflare.cdnjs.com/foo
And I realised that they lacked the http: or https: in front of them.
Hmm, I thought, and tried implementing them in a local test, and realised that they didn't work (they resolved // to be file://, though it was supposed to be http:).
Then when I uploaded this to my testing server, it worked (resolved // to be http://).
So I was wondering, why would anybody write it without the protocol?
Thanks.
(Technically, it's not the "protocol", but the URI scheme)
For HTTP, excluding the scheme means that the UA will use the current scheme (and therefore protocol) to retrieve the file, which means some copy + pasted code can be re-used for both HTTP and HTTPS (or even SPDY) requests without triggering the "Partially secure page" warnings in browsers.
Depending on the user's security settings, browsers will often present a warning if a page serves up mixed content (both HTTP and HTTPS). Of course, you could just code your HTML using the same protocol that you intend the page to be hosted with. However, it's not uncommon to use the same HTML in both secure and non-secure portals. Furthermore, you'd really prefer your HTML to be agnostic to the underlying protocol.
Writing CDN links like this makes sure that the CDN request uses the same protocol as the host page.

Client side includes on local machine

I obviously can't use server side languages, this is just a page on my desktop.
I tried using AJAX with jquery, but I get the following error message
Sorry but there was an error: 0 [Exception... "Access to restricted URI denied" code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" location: "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js Line: 4"]
It has to do with the browser not loading scripts because it's hosted locally or something. So is there any way I can include files on a local machine without installing web server software?
This is an XSS error. You can't make http requests to third party sites (urls not on your domain). You would need to use a proxy to make requests to the page (or have the owner allow your site to make XSS requests).
Shameless plug of a library that I wrote the solve similar problem. We wanted to be able to splice HTML files for backend implementations without the overhead of a local HTTP server implementing server side includes. This library works on HTTP or local filesystem. But, as the repository README notes, you'll have to enable a --allow-file-access-from-files flag to your Chrome runtime. Other browsers work out of box.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
The above will take the contents of /path/to/include.html and replace the div with it.

Least complicated way to get full file paths with Javascript

This has been asked a lot of times already: I need to get the full file path via a web-page. The use case is an application running on the same machine as the browser (i.e. the application starts a local HTTP server and fires up the browser.) File-paths are of course valid and the same for both client/server now. The use case it that the user selects a file and then the server process does some computation on it, and the input files are typically large (read: several GiB in size.)
The easiest thing would be to directly access the path using , but for security reasons, this is disabled. I'm looking now for the least intrusive workaround to this problem. The target browser in question is Chrome. I'm fine if the user has to click "accept" once on some security warning, as long as I can ensure that it won't appear again.
Do I have to write an extension, NSPlugin, can I use some special header magic to mark my page as "local", is there some security setting I can set? The less the client has to do the better, and I would prefer some "click here to allow access ..." solution above everything else. Can I directly install an extension from the server process that would do this (after the user clicks accept?)
Is it possible to do this with a Java applet/Flash? That would be the easiest solution, and clients are guaranteed to have Flash installed (as it is bundled in Chrome...)
You can create Java applet for tasks like this and self-sign it. User will have to allow it to run, but then you will be able to access applet's function that will return file path string via Javascript.
Clearly file io on the client's system is forbidden from JavaScript. If this wasn't the case it would be absolutely trivial to hack every web browser that visits your website.
Battlefiled 3 is controlled though the browser. To do this EA wrote a browser extension for the top three browsers. But that's resource intensive. If you just care about chrome you can use an addon, and for that i suggest using the NPAPI.
And as MOleYArd said, Java is a good solution and probably more common than an extension or addon.

Sharing one JavaScript file among several domains

Problem definition:
Server is an embedded system with no access to Internet.
Each server is managed by web interface which uses JavaScript.
Each server has a local copy of JQuery library.
Clients (browsers) are connected to embedded systems (servers) via a very slow connection.
Clients have the latest browsers (HTML5, CSS3, JavaScript 1.8.5)
Clients are not connected to Internet either.
Clients can't access multiple servers at the same time (servers are in distant locations and most probably a client can only access one server and nothing else, but later that day the client may go to another location and connect to another server).
Each server has an IP address (not necessarily in the same range) and no DNS name.
Every time the client connects to an embedded server, it fetches all the files including the huge JQuery library (huge=~90KB)
Question:
The JQuery library is too big for this slow connection but one-time download is acceptable. However, we don't want the clients to download it every time they connect to each new server. The JQuery on all these devices is the same. But apparently the browser cache is domain based. How can we cache the JQuery library so that the client doesn't have to download the JQuery every time it connects to a new server?
just link to it in one place...
for example, if you have a single server, http://1.2.3.4/ that you want to designate as your CDN, put jQuery on it, and link to it in your scripts using <script src="http://1.2.3.4/jquery.min.js"></script>
you could link it to the ip in your link tag. The server does not have to have access to that access or anything, and so all the clients will geht the jquery from the same server all the time and so it is cached.
Here is a simple solution: All your customers must edit their /etc/hosts file (Google for where you can find it on Windows) and put a line like this in their config:
1.2.3.4 jquery-from-closest-server.com
Each client must figure out the closest server which has jQuery and replace 1.2.3.4 with its IP address.
In your HTML code, always use the link http://jquery-from-closest-server.com/jquery.js
To be safe, you may want to register jquery-from-closest-server.com for those customers which do have Internet access.
When the browser asks for the file, it will use /etc/hosts to resolve the IP address. Since the domain name will be the same for all your embedded devices (changes in the IP address are ignored by the browser), the script will be downloaded once for all clients.
Note that this means you can never upgrade to a newer version of jQuery. The problem is that you'd have to replace it on all embedded devices at the same time because there is no telling from which server the customers are downloading it from.
If that bothers you (and it will in about four months after you discovered the first serious bug), here is another solution: Instead of serving the HTML from your embedded device, distribute a static web app (a set of HTML files and JavaScript) which customer can install in their desktop. Use AJAX and iframes to replace parts of the static web app with data from your embedded device.
Advantages:
very fast (no downloads at all)
only little code on the embedded device
easy upgrade strategy
No deadlocks when you need to upgrade either the embedded devices or your controller app.
[EDIT] PS: Consider to compress jQuery with gzip. That leaves you with a 33KB file. All HTML5 browsers can decode compressed files, you just have to tell them by setting the necessary HTTP headers.
Apparently there is no standard way to include JQuery in our project so we chose to replace JQuery with a smaller similar library. These are the options:
JQuery mobile is a better fit for our project since it has a smaller size and can do almost everything we need from JQuery.
Zepto.js is also another suitable replacement.
JQuip is a stripped down version of JQuery that can help our specific project.

Categories

Resources