For development purposes, I'd like to be able to easily load locally-stored scripts into the browser instead of having to copy-paste to the console.
Creating a new <script> element isn't working, it gives a Not allowed to load local resource: file://.... error (in Chrome).
Also, creating a userscript won't work--I'd have to re-install it every time I make an edit.
Is there an alternative way to easily load a local script via a bookmarklet/etc?
In Chrome, you can create an extension that holds all of the local files that you need to load. It will make your files accessible via chrome-extension://... instead of file://...
Make a file named manifest.json in a new folder and fill it with:
{
"name": "File holder",
"manifest_version": 2,
"version": "1.0",
"web_accessible_resources": ["test.js", "other.js", "yetanother.js"]
}
Then, put all the scripts you want to load in that new directory, and make sure they are included in the web_accessbile_reources manifest list. Load the extension by going to chrome://extensions, enabling Developer Mode, and selecting the new folder with Load unpacked extension....
Now you can access all the files in your extension directory using chrome-extension://[app_id]/[file_name], where "app_id" is the hash listed for the extension on the chrome://extensions page. Note that because the protocols and hostnames differ from where you've doing your actual work (unless you decide to do all your development in the extension folder, which might be acceptable to you), the extension resources are cross-domain and can only be loaded via <script> tag.
Now from the console, you can do:
var s = document.createElement("script");
s.src = "chrome-extension://aefigdoelbemgaedgkcjpcnilbgagpcn/test.js";
document.body.appendChild(s);
(Assuming your file is test.js and your app id is aefigdoelbemgaedgkcjpcnilbgagpcn.)
It's a quite bit to type, I know, but perhaps you can store the chrome-extension://[app_id] part as a shorthand variable?
Sadly, Chrome doesn't allow you to load local files via AJAX; however, you can work around this limitation by launching the browser with the flag --disable-web-security (details vary per host operating system).
run chrome as:
chrome.exe --allow-file-access-from-files
from CLI
you need to run local http server
this is a good document for this:
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server
Have you tried a relative path from your page to your js file liek so...
src='/js/javascript.js'
Related
Below code,
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script type="text/javascript">
console.log(jQuery);
</script>
works fine in firefox browser after src is modified to "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"(remote file) or "../js/jquery.min.js"(local file)
Otherwise, dev console gives Reference error: jQuery is not defined
I would like to test the code with remote library but not local
How do I understand this problem?
Leaving the scheme off the URL means that it is scheme relative.
If the HTML document is loaded over HTTP then the JS will be too.
If the HTML document is loaded over HTTPS then the JS will be too.
If the HTML document is loaded over FILE then … the JS won't be because file://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js doesn't exist.
Do your local testing on a local web server, don't load your HTML directly from your file system.
As mentioned by Mosh Feu, if you run a file locally, without a webserver, you cannot use protocol relative paths to load jQuery. That's because it is trying to find a local reference: file://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js.
Well, you could if you have jQuery locally in a folder /some/where/jQuery.js and you reference it with <script src="//some/where/jQuery.js>
So yes, if you're running pages from the disk directly, you must specify the protocol if you want jQuery from a CDN. See the first comment on http://www.paulirish.com/2010/the-protocol-relative-url/
Save yourself some trouble, install a local web server.
You must be viewing the file locally without using a web server which results in a wrong URL when the protocol is not explicitly specified.
I'm working on a Chrome App, and I have a script file that's saved in the app's sandboxed filesystem. (It's available via a URL filesystem:chrome-extension_****/Persistent/script.js
I'm able to use Chrome's FileSystemAPI to read the file in the main app window. However, I need it to be accessible and executable in a sandboxed page.
I have the following in my manifest -
"sandbox": {
"pages": ["sandboxed_page.html"],
"content_security_policy": "sandbox allow-scripts;"
},
And I'm using the page like this:
<iframe id="sandbox_frame" seamless="seamless" src="sandboxed_page.html" sandbox="allow-scripts"></iframe>
I tried loading the file in the main app window, use window.URL.createObjectURL() to convert it to a blob: URL, and passed this URL via postMessage() to the sandbox. In the sandbox, I'm trying to load the URL into a <script> element. I get an error saying Not allowed to load local resource: blob:chrome-extension%3A//...
The other option (which is working) is load the contents of script.js in the main app, and send the entire string through postMessage(). Not sure this is a good idea, as script.js could get pretty big.
Am I doing something wrong, or is loading local scripts in sandboxes prohibited by Chrome's security policies?
I went through https://developer.chrome.com/apps/app_external, but there's no mention of sending the external resources to the sandbox.
Sandboxed pages execute in a unique origin i.e. one that is different from the App itself, and you can't access filesystem URLs across different origins. The same goes for object URLs created from those files.
You're basically stuck with the postMessage approach, though you may be able to make it more efficient by transfering it as an ArrayBuffer rather than copying the data as a string. See https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects).
Is there a way i can define my script tag to use absolute path instead of relative path so that my JavaScript files are loaded from a network location?
This is what i have tried:
<script src="file:\\\MyDFSDirectory\Test\TestApp\Scripts\jquery-1.7.1.js"></script>
This does not work. in FF, i get the error Security Error: Content at http://localhost/Test/Test.html may not load or link to file:\\\MyDFSDirectory\Test\TestApp\Scripts\jquery-1.7.1.js
In IE, I dont see the file being downloaded. In Network Tab (IE Dev Toolbar), it shows Received 0 B. If i take the URL and paste it in the File Explorer, it opens the JS file.
What am i missing here?
You are indeed running up against the security model of the browsers. The only way around this is to run a web server locally and serve up the files that way.
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.
Just had a quick question to throw out and see if there was a solution for this...
Let's pretend I have no access to the server.
I load up a webpage and find out that they have a Javascript file loading from a subfolder (let's say /scripts/js/some.js)
Now, I want to make changes to this file locally and test it against the whole site without downloading the entire site to a local folder.
Does anyone know of a way I can override the loading of that remote js file in favor of a local/edited copy of it?
Try using noscript or adblock to block the server side script from loading. Then use greasemonkey to load your own script.
I actually found a solution for this. Posting details for anyone that comes here looking for it.
Privoxy (www.privoxy.org/) [Free] Allows this for the most part through a redirect. Though Firefox may block the redirect depending on where you put it. This means you most likely will not be able to save the file locally and reference it via file://etc/
( I wish I had a way to tell you how to statically fiddle with JavaScript on web pages you have limited access to... but I have not found it. If an answer comes along I will accept it over this. )
Of course, you have to set up Privoxy, and use it as a local proxy server. It's pretty simple if you only use it temporarily: Just point your browser to proxy 127.0.0.1 on port 8118 with it running.
You have to add a redirect "default action" (Options > Edit Default Actions) to redirect the browser to use your new copy:
{ +redirect{/newLocation/some.js} }
/scripts/js/some.js
If you want a way to use a local file instead of a remote file (in any web browser), I highly recommend Charles Web Proxy. http://www.charlesproxy.com/
In Charles, go to the Tools menu and select Map Local. Add a new mapping by entering the address of the file on the web you would like loaded from your disk.
This technique will for all sorts of files (JavaScript, CSS, SWF). Of course you have the option to temporarily disable this feature, and it will only work while Charles is running. Very handy.
While your solution with proxy is somewhat more permanent, I found that with Fiddler you can do it with almost no configuration:
How to replace Javascript of production website with local Javascript?
In a browser that supports FileReader such as Chrome, yes, in combination with 'eval' to execute arbitrary JS. In your HTML add a button for the user to press:
<form>
<input type="file" name="file"
onchange="loadJS(event.target.files);">
</form>
In your scripts add:
function load() {
var reader = new FileReader();
reader.onload = function(evt) {
eval(evt.target.result);
};
reader.readAsText(files[0]);
}