I would like to trigger download with window.open() function in javascript in local.
The path should start with "/".
I provide URL with / to start, however, it seems like window.open() function ignore the first /.
Is there a way to make it read the / , so that i can trigger download?
A URL starting with a / is a relative URL with an absolute path. It ignores the existing path on the URL, and calculates the new one starting from the end of the port (or hostname if there is no port, localhost in this case).
If you want to make a request to a different URL scheme (in this case file: instead of http:) then you need to use an absolute URL (i.e. state the new URL scheme explicitly).
NB: Many browsers will block requests to file: scheme URLs triggered by pages which were not served using the file: scheme for security reasons.
Try use this :
window.open('file:///D:/Examples/file2.extension')
It work for me with a local file
For security reasons browsers block opening local files using window.open().
In order to display local file you must urge user to manually choose file you want them to open. I know that is not the desirable solution but it is how can it work. One of implementation with FileReader is in this answer: How to open a local disk file with JavaScript?
Related
I know it's possible to force reload from server using location.reload(true). However, let's say I used that to refresh index.html. If index.html loads a bunch of javascript files, those are still coming from the cache for me. Is there any way to ignore the cache for the duration of a request?
My use case is that I'm doing AB testing on my app, and want to provide a way for users to go back to the old version if something isn't working. But some of the URLs are the same, even though the files between versions are different. It would be nice to be able to handle this in JS rather than having to change every URL on the new version.
There is actually at least 535 different ways to reload a page via javascript, FYI ;).
Have you tried to put document on front? document.location.reload(true);
Try also this other option:
window.location.href = window.location.href;
or
history.go(0);
Sure, both are soft reload, but seems to work in certain situation.
If nothing works, you have to append random data to the url (like timestamp) to force the download from server, bypassing the cache.
If you want to bypass browser taking js files from cache, you need to fetch from server not just files like script.js but rather script.12345.js When you update your file on server, you change file's hash number to let's say script.54321.js And browser understands that the file is different, it must download it again. You can actually use Webpack for this purpose to automate things. In output instead of {filename: bundle.js} you write {filename: bundle.[hash].js}
I have following url to be build,
http://localhost/myweb/cart/index.php
I want to get the http://localhost/myweb/ bit build dynamically.
To do that on my live web site which is http://www.myweb.com/cart/index.php I can use the following JavaScript code,
var http = location.protocol;
var slashes = http.concat("//");
var host = slashes.concat(window.location.hostname);
But how do I get my development environment to work since it has http://localhost/myweb/? If I run the above code it will give me http://localhost/ only.
Any suggestions?
window.location.pathname is the thing you search for.
I would suggest you to read the MDN description of window.location. Like everything else in MDN, this is also really straightforward and informative.
If you know that the URL has an unnecessary index.html part at the end you can:
var path = window.location.pathname.split('/');
path.pop();
path.join('/');
or you can slice it (since it is generally faster):
path.slice(0,path.lastIndexOf('/')+1)
EDIT:
Seeing your new question I can say that what you want can't be done consistently and safely by only the current URL.
You need the http://localhost/myweb/ part, which is the URL root of your application. In javascript you are able to get the protocol and domain of the url. On your live site these 2 match, but if your application resides in a subfolder (like the myweb folder at your localhost), this will fail.
What you need is to somehow identify the application URL (the URL root of your application).
The problem is that by only examining the URL, javascript cannot tell where your application resides.
Let's say you deploy your site to: http://localhost/myweb/site1/
You will have the following URL: http://localhost/myweb/site1/cart/index.php
Javascript can split your URL by the slashes (/) but it has no way of nowing how many subfolders it should select. For example from the URL above your application root can be any of the following: http://localhost/, http://localhost/myweb/, http://localhost/myweb/site1/, http://localhost/myweb/site1/cart/.
By an other approach (which I suggested first) you can drop the end of the URL (in your case the cart/index.php part). This will only work if your URL structure IS very rigid, so all the pages this script is executed on reside in one subfolder.
So it will break on the following URL: http://localhost/myweb/site1/gallery/old/index.php or similar.
Your best bet would be to make this a "config variable" in a separate file which you edit on every location it is deployed to.
Either as a PHP variable ($appRoot = "http://localhost/myweb/") which you generate the javascript with.
Or more simply a javascript variable (var appRoot = 'http://localhost/myweb/'). Make a separate js file, call it something like config.js, add the above line to it and reference it before your other javascripts.
Same question as here but I need to go to local URL's in Firefox
I tried with code like
var url = "file:///E:/Test/Test.htm";
window.location.href = url;
but id didn't work. Tried to go with window.location = url; and also tried with url = "file://E:/Test/Test.htm"; (double "/" instead of triple "/") and still doesn't work.
Thanks
When I try this:
window.location.href = "file:///C:/Users/Cerbrus/Documents/SomeFile.js"
(Yes, it is a valid path.)
Chrome throws me this error:
Not allowed to load local resource: file:///C:/Users//Documents/File.js
This is because JavaScript does not have access to local files (due to it being sandboxed), and you're setting the new url with JavaScript.
"SandBoxed" means a technology has restricted (or no) access outside a certain set of bounds. In the case of browsers, this means that the code that runs on the page can not access files on your system (Otherwise, it would be easy to "steal" data, by just having a look at the user's file system).
However,
Say, I have 2 files:
C:/Test/Test.htm
C:/Test/Test1.htm
Test.htm contains only this:
<script>
window.location = "file:///C:/Test/Test1.htm";
</script>
This will actually redirect to Test1.htm, since the target file is on the same domain as where the source file's from.
I guess its not allowed to load local resource from javascript
Unless you have a local http server running:
var url = "http://localhost/MySite/Default.aspx";
window.location.href = url;
It will work
You cannot access the file from the local system. Since the Browser works in the sandbox mode and you cannot breach the sandbox and reach the local file system since it would violate the security. Either try to directly load using an AJAX request else what you are trying to do is not possible due to sandbox restrictions and also does not comply with the security policies.
window.location.href = window.location.pathname + (your local file name or path)
window.open(url); // here url can be anything
I'm trying to create a website that can be downloaded and run locally by launching its index file.
All the files are local, no resources are used online.
When I try to use the AJAXSLT plugin for jQuery to process an XML file with an XSL template (in sub directories), I receive the following errors:
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/data/home.xml. Origin null is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load file:///C:/path/to/XSL%20Website/assets/xsl/main.xsl. Origin null is not allowed by Access-Control-Allow-Origin.
The index file making the request is file:///C:/path/to/XSL%20Website/index.html while the JavaScript files used are stored in file:///C:/path/to/XSL%20Website/assets/js/.
How can I do to fix this issue?
For instances where running a local webserver is not an option, you can allow Chrome access to file:// files via a browser switch. After some digging, I found this discussion, which mentions a browser switch in opening post. Run your Chrome instance with:
chrome.exe --allow-file-access-from-files
This may be acceptable for development environments, but little else. You certainly don't want this on all the time. This still appears to be an open issue (as of Jan 2011).
See also: Problems with jQuery getJSON using local files in Chrome
Essentially the only way to deal with this is to have a webserver running on localhost and to serve them from there.
It is insecure for a browser to allow an ajax request to access any file on your computer, therefore most browsers seem to treat "file://" requests as having no origin for the purpose of "Same Origin Policy"
Starting a webserver can be as trivial as cding into the directory the files are in and running:
python -m http.server
[Edit Thanks #alextercete, for pointing out that it has updated in Python3]
This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.
$.ajaxPrefilter( "json script", function( options ) {
options.crossDomain = true;
});
What about using the javascript FileReader function to open the local file, ie:
<input type="file" name="filename" id="filename">
<script>
$("#filename").change(function (e) {
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function (e) {
// Get all the contents in the file
var data = e.target.result;
// other stuffss................
};
reader.readAsText(e.target.files.item(0));
}
});
</script>
Now Click Choose file button and browse to the file file:///C:/path/to/XSL%20Website/data/home.xml
Here is an applescript that will launch Chrome with the --allow-file-access-from-files switch turned on, for OSX/Chrome devs out there:
set chromePath to POSIX path of "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
set switch to " --allow-file-access-from-files"
do shell script (quoted form of chromePath) & switch & " > /dev/null 2>&1 &"
Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files.
Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).
The way I just worked around this is not to use XMLHTTPRequest at all, but include the data needed in a separate javascript file instead. (In my case I needed a binary SQLite blob to use with https://github.com/kripken/sql.js/)
I created a file called base64_data.js (and used btoa() to convert the data that I needed and insert it into a <div> so I could copy it).
var base64_data = "U1FMaXRlIGZvcm1hdCAzAAQA ...<snip lots of data> AhEHwA==";
and then included the data in the html like normal javascript:
<div id="test"></div>
<script src="base64_data.js"></script>
<script>
data = atob(base64_data);
var sqldb = new SQL.Database(data);
// Database test code from the sql.js project
var test = sqldb.exec("SELECT * FROM Genre");
document.getElementById("test").textContent = JSON.stringify(test);
</script>
I imagine it would be trivial to modify this to read JSON, maybe even XML; I'll leave that as an exercise for the reader ;)
You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).
use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.
if it doesnt take you to the file, then add the name of the file to the urs. like this:
https://127.0.0.1:8887/fileName.txt
link to web server for chrome: click me
If you only need to access the files locally then you can include the exact path to the file, rather than using
../images/img.jpg
use
C:/Users/username/directoryToImg/img.jpg
The reason CORS is happening is because you are trying to traverse to another directory within a webpage, by including the direct path you are not changing directory, you are pulling from a direct location.
I have a plugin that runs off my customer's websites. The plugin is at http://mycompany.com/Tool.js, and needs to pull in some images. The problem is that the javascript seems to try to pull images from the customer's site, rather than from my own site. Here is the JS:
button.style.cssText = 'position:absolute;top:-20px;right:-20px;background-image:url(/Resource/Button.png);
In the above JS, the retrieval URL is CUSTOMER.com/Resource/Button.png (the site where the plugin runs), rather than my sites mycompany.com/Resource/Button.png.
Note that I cannot use absolute paths, as they become a pain between environments (test/prod) and also because my image retrieval must use http/https based on the client environment (otherwise you can errors if http is used on an https site).
Just replace it with
background-image:url(http://mycompany.com/Resource/Button.png);
Instead of using Javascript or anything you can actually just use // before the URL in the stylesheet and it will use http or https depending on how the client came to the site. You can do the same on the HTML page when you link the stylesheet to the page. So your HTML page will be:
<link href="//mycompany.com/stylesheet" />
And in your stylesheet you can have
background-image:url(//mycompany.com/Resource/Button.png);
edit
I forgot to mention that you can do the same when attaching javascript files to the page as well.
For eg: <script type="text/javascript" src="//mycompany.com/javascript"></script>
The javascript will run in the context of where it runs, not where it is downloaded from. If the resource URL is not absolute, the domain will be assumed to be the one your browser is currently accessing.
You'll need an absolute URL. E.g. http://mycompany.com/Resource/Button.png
absolute path should be included!!
switch (window.location.protocol) {
case "http:":
button.style.cssText = 'position:absolute;top:-20px;right:-20px;background-image:url(http://yourcompany.com/Resource/Button.png);break;
case "https:":
button.style.cssText = 'position:absolute;top:-20px;right:-20px;background-image:url(https://yourcompany.com/Resource/Button.png);break;
}