Go to local URL with Javascript - javascript

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

Related

window.open for local file path

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?

Executing a JavaScript file directly from the browser

This sounds like a trivia question but I really need to know.
If you put the URL of an HTML file in the Location bar of your browser, it will render that HTML. That's the whole purpose of a browser.
If you give it a JPG, or a SWF, or even PDF, it will do the right things for those datatypes.
But, if you give it the URL of a JavaScript file, it will display the text of that file. What I want is for that file to be executed directly.
Now, I know that if you use the javascript: protocol, it will execute the text of the URL, but that isn't what I need.
I could have the URL point to an HTML file consisting of a single <script> tag that in turn points to the JavaScript file, but for occult reasons of my own, I cannot do that.
If the file at http://example.com/file.js consists entirely of
alert("it ran");
And I put that URL in the Location bar, I want "it ran" to pop up as an alert.
I'm skeptical that this is possible but I'm hoping-against-hope that there is a header or a MIME type or something like that that I can set and miraculously make this happen.
This is not possible. The browser has no idea what context the JavaScript should run in; for example, what are the properties of window? If you assume it can come up with some random defaults, what about the behavior of document? If someone does document.body.innerHTML = "foo" what should happen?
JavaScript, unlike images or HTML pages, is dependent on a context in which it runs. That context could be a HTML page, or it could be a Node server environment, or it could even be Windows Scripting Host. But if you just navigate to a URL, the browser has no idea what context it should run the script in.
As a workaround, perhaps use about:blank as a host page. Then you can insert the script into the document, giving it the appropriate execution context, by pasting the following in your URL bar:
javascript:(function () { var el = document.createElement("script"); el.src = "PUT_URL_HERE"; document.body.appendChild(el); })();
Or you can use RunJS: https://github.com/Dharmoslap/RunJS
Then you will be able to run .js files just with drag&drop.
Not directly, but you could make a simple server-side script, e.g. in PHP. Instead of
http://example.com/file.js
, navigate to:
http://localhost/execute_script.php?url=http://example.com/file.js
Of course, you could smallen this by using RewriteRule in Apache, and/or adding another entry in your hosts file that redirects to 127.0.0.1.
Note that this is not great in terms of security, but if you use it yourself and know what you're downloading, you should be fine.
<html>
<head>
<script>
<? echo file_get_contents($_GET['url']); ?>
</script>
</head>
<body>
</body>
</html>
In the address bar, you simply write
javascript:/some javascript code here/;void(0);
http://www.javascriptkata.com/2007/05/01/execute-javascript-code-directly-in-your-browser/
Use Node.js.
Download and install node.js and create a http/s server and write down what you want to display in browser.
use localhost::portNumber on server as url to run your file.
refer to node js doc - https://nodejs.org/dist/latest-v7.x/docs/api/http.html
Run - http://localhost:3000
sample code below :
var http = require("http");
var server = http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.end("hello user");
}); server.listen(3000);`
you can write your own browser using qt /webkit and do that.
when user enters a js file in url location you can read that file and execute the javascript .
http://code.google.com/apis/v8/get_started.html is another channel.
not sure if it meets ur need.

XMLHttpRequest cannot load file:///. Origin null is not allowed by Access-Control-Allow-Origin [duplicate]

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.

Use javascript to get the directory of a file

I am using an input of type=file and I am trying to figure out how to extract the file location from it. I am using this code:
file = $("#uploadFiles").attr("files")[0];
var fileName = file.fileName;
var formData = 'uploadFile=' + fileName;
and when i alert formData, it says "uploadFile=temp.jpg"
What I want is the alerted message to be something like:
"uploadFile=C:\user\doug\documents\pictures\temp.jpg"
But I don't know the attribute of the file object to put in for file.fileName
Generally, you can only rely on the filename being accessible - used mainly as a preliminary extension checking (e.g. (jpe?g|png|gif)$) on the client side (which only serves to benefit the user, to stop them from uploading a 5mb file that will be not validate on the server anyway).
You can access whatever the browser will give you with...
jQuery
$('file[type=input]').val();
JavaScript
document.getElementById('file-input').value;
For security reasons, this is completely impossible in modern browsers.

starting file download with JavaScript

Let's say I have download links for files on my site.
When clicked these links send an AJAX request to the server which returns the URL with the location of the file.
What I want to do is direct the browser to download the file when the response gets back. Is there a portable way to do this?
We do it that way:
First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
download
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter.
We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
Tested cross browser support (including mobile!)
It supports POST and GET requests in a manner similar to jQuery's AJAX API
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
Just call window.location.href = new_url from your javascript and it will redirect the browser to that URL as it the user had typed that into the address bar
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script?
The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
If this is your own server application then i suggest using the following header
Content-disposition: attachment; filename=fname.ext
This will force any browser to download the file and not render it in the browser window.
Try this lib https://github.com/PixelsCommander/Download-File-JS it`s more modern than all solutions described before because uses "download" attribute and combination of methods to bring best possible experience.
Explained here - http://pixelscommander.com/en/javascript/javascript-file-downliading-ignore-content-type/
Seems to be ideal piece of code for starting downloading in JavaScript.
A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.
If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.
To get around the security flaw in the top-voted answer, you can set the iframe src directly to the file you want (instead of an intermediate php file) and set the header information in an .htaccess file:
<Files *.apk>
ForceType application/force-download
Header set Content-Disposition attachment
Header set Content-Type application/vnd.android.package-archive
Header set Content-Transfer-Encoding binary
</Files>
I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.
Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.
In relation to the top answer I have a possible solution to the security risk.
<?php
if(isset($_GET['path'])){
if(in_array($_GET['path'], glob("*/*.*"))){
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
}
}
?>
Using the glob() function (I tested the download file in a path one folder up from the file to be downloaded) I was able to make a quick array of files that are "allowed" to be downloaded and checked the passed path against it. Not only does this insure that the file being grabbed isn't something sensitive but also checks on the files existence at the same time.
~Note: Javascript / HTML~
HTML:
<iframe id="download" style="display:none"></iframe>
and
<input type="submit" value="Download" onclick="ChangeSource('document_path');return false;">
JavaScript:
<script type="text/javascript">
<!--
function ChangeSource(path){
document.getElementByID('download').src = 'path_to_php?path=' + document_path;
}
-->
</script>
I'd suggest window.open() to open a popup window. If it's a download, there will be no window and you will get your file. If there is a 404 or something, the user will see it in a new window (hence, their work will not be bothered, but they will still get an error message).
Why are you making server side stuff when all you need is to redirect browser to different window.location.href?
Here is code that parses ?file= QueryString (taken from this question) and redirects user to that address in 1 second (works for me even on Android browsers):
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
(window.onload = function() {
var path = urlParams["file"];
setTimeout(function() { document.location.href = path; }, 1000);
});
</script>
If you have jQuery in your project definitely remove those window.onpopstate & window.onload handlers and do everything in $(document).ready(function () { } );

Categories