How to register a url protocol handler in Node.js - javascript

I am developing a command line node module and would like to be able to launch it via links on a website.
I want to register a custom protocol my-module:// such that links would have the following format: my-module://action:some-action and clicking on them would start the node package.
If there isn't a node API for this (I'm sure there won't be) then is there a way I can do it from node by invoking system commands?
It must work on Windows, Linux, and MacOS.

Its an interesting idea. I don't think there is currently a cross platform node.js solution out there. I did come across this thread of people asking for the same thing:
https://github.com/rogerwang/node-webkit/issues/951
Electron now supports it with the app.setAsDefaultProtocolClient API (since v0.37.4) for macOS and Windows.
It wouldn't be terribly difficult to write the library to do this.
Windows:
On the windows side you'd have to register the app as the application that handles that URI scheme.
You'll need to set up a registry entry for your application:
HKEY_CLASSES_ROOT
alert
(Default) = "URL:Alert Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "alert.exe,1"
shell
open
command
(Default) = "C:\Program Files\Alert\alert.exe" "%1"
Then, when your application is run by windows, you should be able to see the arguments in process.argv[]. Make sure that you launch a shell to run node, not just your application directly.
Original MSDN article
Note this requires administrator privileges and sets the handler system-wide. To do it per user, you can use HKEY_CURRENT_USER\Software\Classes instead, as the Electron's implementation does it.
Apple:
The cited "OS X" article in the github comment is actually for iOS. I'd look at the following programming guide for info on registering an application to handle a URL scheme:
Apple Dev Documentation
In summary, you'll need to create a launch service and populate the .plist file with CFBundleURLTypes, this field is an array and should be populated with just the protocol name i.e. http
The following Super User Question has a better solution, but is a per user setting.
"The file you seek is ~/Library/Preferences/com.apple.LaunchServices.plist.
It holds an array called LSHandlers, and the Dictionary children that define an LSHandlerURLScheme can be modified accordingly with the LSHandlerRole."
Linux:
From what I can tell, there are several ways to accomplish this in Linux (surprise?)
Gnome has a tool that will let you register a url handler w3 archives
gconftool-2 -t string -s /desktop/gnome/url-handlers/tel/command "bin/vonage-call %s"
gconftool-2 -s /desktop/gnome/url-handlers/tel/needs_terminal false -t bool
gconftool-2 -t bool -s /desktop/gnome/url-handlers/tel/enabled true
Some of the lighter weight managers look like they allow you to create fake mime types and register them as URI Protocol handlers.
"Fake mime-types are created for URIs with various scheme like this:
application/x-xdg-protocol-
Applications supporting specific URI protocol can add the fake mime-type to their MimeType key in their desktop entry files. So it's easy to find out all applications installed on the system supporting a URI scheme by looking in mimeinfo.cache file. Again defaults.list file can be used to specify a default program for speficied URI type." wiki.lxde.org
KDE also supports their own method of handling URL Protocol Handlers:
Create a file: $KDEDIR/share/services/your.protocol and populate it with relevant data:
[Protocol]
exec=/path/to/player "%u"
protocol=lastfm
input=none
output=none
helper=true
listing=
reading=false
writing=false
makedir=false
deleting=false
from last.fm forums of all places
Hope that helps.

Here's how I did on Mac OS with an application NW.js :
Open the app /Applications/Utilities/Script Editor
type the following code in the editor
on open location this_URL
do shell script "/Applications/X.app/Contents/MacOS/x '" & this_URL & "'"
end open location
Replace X by the name of your App.
Save the script as an Application Bundle anywhere
Go to the script, right click then 'Show Package Contents' then edit Contents/info.plist
Add these lines at the end of the file, just before </dict></plist> :
<key>CFBundleIdentifier</key>
<string>com.mycompany.AppleScript.AppName</string> <!-- edit here -->
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>AppName</string> <!-- edit here -->
<key>CFBundleURLSchemes</key>
<array>
<string>myurlscheme</string> <!-- your url scheme here -->
</array>
</dict>
</array>
You can now open a link starting with myurlscheme: and see your app is opening!

Edit :
Looks like the module has changed the registration process for good:
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // sets protocol for your command , testproto://**
command: `node ${path.join(__dirname, './tester.js')} $_URL_`, // this will be executed with a extra argument %url from which it was initiated
override: true, // Use this with caution as it will destroy all previous Registrations on this protocol
terminal: true, // Use this to run your command inside a terminal
script: false
}).then(async () => {
console.log('Successfully registered');
});
Original Answer :
There is an npm module for this purpose.
link :https://www.npmjs.com/package/protocol-registry
So to do this in nodejs you just need to run the code below:
First Install it
npm i protocol-registry
Then use the code below to register you entry file.
const path = require('path');
const ProtocolRegistry = require('protocol-registry');
console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
protocol: 'testproto', // set your app for testproto://**
command: `node ${path.join(__dirname, './index.js')}`, // this will be executed with a extra argument %url from which it was initiated
}).then(async () => {
console.log('Successfully registered');
});
Then suppose someone opens testproto://test
then a new terminal will be launched executing :
node yourapp/index.js testproto://test

Related

CORS policy error on file in same folder as HTML [duplicate]

I am getting the following error:
XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP.
I realize that this question has been answered before, but I still have not found a solution to my problem. I tried running chrome.exe --allow-file-access-from-files from the command prompt, and moved the file to the local file system, but I still get the same error.
I appreciate any suggestions!
If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Here are some options that I use.
Test your web page locally on Firefox, then deploy to your host.
or: Run a local server
Test on Firefox, Deploy to Host
Firefox currently allows Cross Origin Requests from files served from your hard drive
Your web hosting site will allow requests to files in folders as configured by the manifest file
Run a Local Server
Run a server on your computer, like Apache or Python
Python isn't a server, but it will run a simple server
Run a Local Server with Python
Get your IP address:
On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
Type the command: ipconfig and hit Enter.
Look for: IPv4 Address . . . . . . . . 12.123.123.00
There are websites that will also display your IP address
If you don't have Python, download and install it.
Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.
If you need to get back to the C:\ Root directory - type cd/
type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
Type something like: path c:\python27 %path%
%path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
Create the new path FROM the folder where you want to serve the files.
Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
If you leave the port empty, it defaults to port 8000
If the Python server starts successfully, you will see a msg.
Run You Web Application Locally
Open a browser
In the address line type: http://your IP address:port
http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
If the server is working, you will see a list of your files in the browser
Click the file you want to serve, and it should display.
More advanced solutions
Install a code editor, web server, and other services that are integrated.
You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.
I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.
Simple Solution
If you are working with pure html/js/css files.
Install this small server(link) app in chrome. Open the app and point the file location to your project directory.
Goto the url shown in the app.
Edit: Smarter solution using Gulp
Step 1: To install Gulp. Run following command in your terminal.
npm install gulp-cli -g
npm install gulp -D
Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.
var gulp = require('gulp');
var bs = require('browser-sync').create();
gulp.task('serve', [], () => {
bs.init({
server: {
baseDir: "./",
},
port: 5000,
reloadOnRestart: true,
browser: "google chrome"
});
gulp.watch('./**/*', ['', bs.reload]);
});
Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command
npm install browser-sync gulp --save-dev
Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command
gulp serve
To add to Alan Wells's elaborate answer here is a quick fix
Run a Local Server
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
If you are using vscode, you can easily start a liver server. Click liver server at the bottom of the page, once the server is started, vscode will tell the port the project is running. Do ensure your project folder is the workspace
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
http://localhost//myAPIProject
Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

Can XMLHttpRequest() be used on a static webpage or must it be on server? [duplicate]

I'm trying to load a 3D model, stored locally on my computer, into Three.js with JSONLoader, and that 3D model is in the same directory as the entire website.
I'm getting the "Cross origin requests are only supported for HTTP." error, but I don't know what's causing it nor how to fix it.
My crystal ball says that you are loading the model using either file:// or C:/, which stays true to the error message as they are not http://
So you can either install a webserver in your local PC or upload the model somewhere else and use jsonp and change the url to http://example.com/path/to/model
Origin is defined in RFC-6454 as
...they have the same
scheme, host, and port. (See Section 4 for full details.)
So even though your file originates from the same host (localhost), but as long as the scheme is different (http / file), they are treated as different origin.
Just to be explicit - Yes, the error is saying you cannot point your browser directly at file://some/path/some.html
Here are some options to quickly spin up a local web server to let your browser render local files
Python 2
If you have Python installed...
Change directory into the folder where your file some.html or file(s) exist using the command cd /path/to/your/folder
Start up a Python web server using the command python -m SimpleHTTPServer
This will start a web server to host your entire directory listing at http://localhost:8000
You can use a custom port python -m SimpleHTTPServer 9000 giving you link: http://localhost:9000
This approach is built in to any Python installation.
Python 3
Do the same steps, but use the following command instead python3 -m http.server
VSCode
If you are using Visual Studio Code you can install the Live Server extension which provides a local web server enviroment.
Node.js
Alternatively, if you demand a more responsive setup and already use nodejs...
Install http-server by typing npm install -g http-server
Change into your working directory, where yoursome.html lives
Start your http server by issuing http-server -c-1
This spins up a Node.js httpd which serves the files in your directory as static files accessible from http://localhost:8080
Ruby
If your preferred language is Ruby ... the Ruby Gods say this works as well:
ruby -run -e httpd . -p 8080
PHP
Of course PHP also has its solution.
php -S localhost:8000
In Chrome you can use this flag:
--allow-file-access-from-files
Read more here.
Ran in to this today.
I wrote some code that looked like this:
app.controller('ctrlr', function($scope, $http){
$http.get('localhost:3000').success(function(data) {
$scope.stuff = data;
});
});
...but it should've looked like this:
app.controller('ctrlr', function($scope, $http){
$http.get('http://localhost:3000').success(function(data) {
$scope.stuff = data;
});
});
The only difference was the lack of http:// in the second snippet of code.
Just wanted to put that out there in case there are others with a similar issue.
Just change the url to http://localhost instead of localhost. If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome. That will fix the issue.
I'm going to list 3 different approaches to solve this issue:
Using a very lightweight npm package: Install live-server using npm install -g live-server. Then, go to that directory open the terminal and type live-server and hit enter, page will be served at localhost:8080. BONUS: It also supports hot reloading by default.
Using a lightweight Google Chrome app developed by Google: Install the app, then go to the apps tab in Chrome and open the app. In the app point it to the right folder. Your page will be served!
Modifying Chrome shortcut in windows: Create a Chrome browser's shortcut. Right-click on the icon and open properties. In properties, edit target to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession" and save. Then using Chrome open the page using ctrl+o. NOTE: Do NOT use this shortcut for regular browsing.
Note: Use http:// like http://localhost:8080 in case you face error.
Use http:// or https:// to create url
error: localhost:8080
solution: http://localhost:8080
In an Android app — for example, to allow JavaScript to have access to assets via file:///android_asset/ — use setAllowFileAccessFromFileURLs(true) on the WebSettings that you get from calling getSettings() on the WebView.
fastest way for me was:
for windows users run your file on Firefox problem solved, or
if you want to use chrome easiest way for me was to install Python 3 then from command prompt run command python -m http.server then go to http://localhost:8000/ then navigate to your files
python -m http.server
Easy solution for whom using VS Code
I've been getting this error for a while. Most of the answers works. But I found a different solution. If you don't want to deal with node.js or any other solution in here and you are working with an HTML file (calling functions from another js file or fetch json api's) try to use Live Server extension.
It allows you to open a live server easily. And because of it creates localhost server, the problem is resolving. You can simply start the localhost by open a HTML file and right-click on the editor and click on Open with Live Server.
It basically load the files using http://localhost/index.html instead of using file://....
EDIT
It is not necessary to have a .html file. You can start the Live Server with shortcuts.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server. [On MAC, cmd+L, cmd+O and cmd+L, cmd+C]
Hope it will help someone :)
If you use old version of Mozilla Firefox (pre-2019), it will work as expected without any issues;
P.S. Surprisingly, old versions of Internet Explorer & Edge work absolutely fine too.
For those on Windows without Python or Node.js, there is still a lightweight solution: Mongoose.
All you do is drag the executable to wherever the root of the server should be, and run it. An icon will appear in the taskbar and it'll navigate to the server in the default browser.
Also, Z-WAMP is a 100% portable WAMP that runs in a single folder, it's awesome. That's an option if you need a quick PHP and MySQL server. Though it hasn't been updated since 2013. A modern alternative would be Laragon or WinNMP. I haven't tested them, but they are portable and worth mentioning.
Also, if you only want the absolute basics (HTML+JS), here's a tiny PowerShell script that doesn't need anything to be installed or downloaded:
$Srv = New-Object Net.HttpListener;
$Srv.Prefixes.Add("http://localhost:8080/");
$Srv.Start();
Start-Process "http://localhost:8080/index.html";
While($Srv.IsListening) {
$Ctx = $Srv.GetContext();
$Buf = [System.IO.File]::OpenRead((Join-Path $Pwd($Ctx.Request.RawUrl)));
$Ctx.Response.ContentLength64 = $Buf.Length;
$Ctx.Response.Headers.Add("Content-Type", "text/html");
$Buf.CopyTo($Ctx.Response.OutputStream);
$Buf.Close();
$Ctx.Response.Close();
};
This method is very barebones, it cannot show directories or other fancy stuff. But it handles these CORS errors just fine.
Save the script as server.ps1 and run in the root of your project. It will launch index.html in the directory it is placed in.
I suspect it's already mentioned in some of the answers, but I'll slightly modify this to have complete working answer (easier to find and use).
Go to: https://nodejs.org/en/download/. Install nodejs.
Install http-server by running command from command prompt npm install -g http-server.
Change into your working directory, where index.html/yoursome.html resides.
Start your http server by running command http-server -c-1
Open web browser to http://localhost:8080
or http://localhost:8080/yoursome.html - depending on your html filename.
I was getting this exact error when loading an HTML file on the browser that was using a json file from the local directory. In my case, I was able to solve this by creating a simple node server that allowed to server static content. I left the code for this at this other answer.
It simply says that the application should be run on a web server. I had the same problem with chrome, I started tomcat and moved my application there, and it worked.
I suggest you use a mini-server to run these kind of applications on localhost (if you are not using some inbuilt server).
Here's one that is very simple to setup and run:
https://www.npmjs.com/package/tiny-server
Experienced this when I downloaded a page for offline view.
I just had to remove the integrity="*****" and crossorigin="anonymous" attributes from all <link> and <script> tags
If you insist on running the .html file locally and not serving it with a webserver, you can prevent those cross origin requests from happening in the first place by making the problematic resources available inline.
I had this problem when trying to to serve .js files through file://. My solution was to update my build script to replace <script src="..."> tags with <script>...</script>.
Here's a gulp approach for doing that:
1.
run npm install --save-dev to packages gulp, gulp-inline and del.
2.
After creating a gulpfile.js to the root directory, add the following code (just change the file paths for whatever suits you):
let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');
gulp.task('inline', function (done) {
gulp.src('dist/index.html')
.pipe(inline({
base: 'dist/',
disabledTypes: 'css, svg, img'
}))
.pipe(gulp.dest('dist/').on('finish', function(){
done()
}));
});
gulp.task('clean', function (done) {
del(['dist/*.js'])
done()
});
gulp.task('bundle-for-local', gulp.series('inline', 'clean'))
Either run gulp bundle-for-local or update your build script to run it automatically.
You can see the detailed problem and solution for my case here.
For all y'all on MacOS... setup a simple LaunchAgent to enable these glamorous capabilities in your own copy of Chrome...
Save a plist, named whatever (launch.chrome.dev.mode.plist, for example) in ~/Library/LaunchAgents with similar content to...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>launch.chrome.dev.mode</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/Google Chrome.app/Contents/MacOS/Google Chrome</string>
<string>-allow-file-access-from-files</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
It should launch at startup.. but you can force it to do so at any time with the terminal command
launchctl load -w ~/Library/LaunchAgents/launch.chrome.dev.mode.plist
TADA! 😎 💁🏻 🙊 🙏🏾
Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"
npm install http-server -g
http-server [path] [options]
Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.
er. I just found some official words "Attempting to load unbuilt, remote AMD modules that use the dojo/text plugin will fail due to cross-origin security restrictions. (Built versions of AMD modules are unaffected because the calls to dojo/text are eliminated by the build system.)" https://dojotoolkit.org/documentation/tutorials/1.10/cdn/
One way it worked loading local files is using them with in the project folder instead of outside your project folder. Create one folder under your project example files similar to the way we create for images and replace the section where using complete local path other than project path and use relative url of file under project folder .
It worked for me
Install local webserver for java e.g Tomcat,for php you can use lamp etc
Drop the json file in the public accessible app server directory
Start the app server,and you should be able to access the file from localhost
For Linux Python users:
import webbrowser
browser = webbrowser.get('google-chrome --allow-file-access-from-files %s')
browser.open(url)
url should be like:
createUserURL = "http://www.localhost:3000/api/angular/users"
instead of:
createUserURL = "localhost:3000/api/angular/users"
Many problem for this, with my problem is missing '/' example:
jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/
It's must be: http://localhost:xxx/Product/getList_tagLabels/
I hope this help for who meet this problem.
I have also been able to recreate this error message when using an anchor tag with the following href:
Example a tag
In my case an a tag was being used to get the 'Pointer Cursor' and the event was actually controlled by some jQuery on click event. I removed the href and added a class that applies:
cursor:pointer;
cordova achieve this. I still can not figure out how cordova did. It does not even go through shouldInterceptRequest.
Later I found out that the key to load any file from local is: myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
And when you want to access any http resource, the webview will do checking with OPTIONS method, which you can grant the access through WebViewClient.shouldInterceptRequest by return a response, and for the following GET/POST method, you can just return null.
If you are searching for a solution for Firebase Hosting, you can run the
firebase serve --only hosting command from the Firebase CLI
That's what I came here for, so I thought I'd just leave it here to help like ones.
If your using VS code just trying loading a live server in there. fixed my problem immediately.

D3 chart visible in Firefox but not in Chrome [duplicate]

I'm trying to load a 3D model, stored locally on my computer, into Three.js with JSONLoader, and that 3D model is in the same directory as the entire website.
I'm getting the "Cross origin requests are only supported for HTTP." error, but I don't know what's causing it nor how to fix it.
My crystal ball says that you are loading the model using either file:// or C:/, which stays true to the error message as they are not http://
So you can either install a webserver in your local PC or upload the model somewhere else and use jsonp and change the url to http://example.com/path/to/model
Origin is defined in RFC-6454 as
...they have the same
scheme, host, and port. (See Section 4 for full details.)
So even though your file originates from the same host (localhost), but as long as the scheme is different (http / file), they are treated as different origin.
Just to be explicit - Yes, the error is saying you cannot point your browser directly at file://some/path/some.html
Here are some options to quickly spin up a local web server to let your browser render local files
Python 2
If you have Python installed...
Change directory into the folder where your file some.html or file(s) exist using the command cd /path/to/your/folder
Start up a Python web server using the command python -m SimpleHTTPServer
This will start a web server to host your entire directory listing at http://localhost:8000
You can use a custom port python -m SimpleHTTPServer 9000 giving you link: http://localhost:9000
This approach is built in to any Python installation.
Python 3
Do the same steps, but use the following command instead python3 -m http.server
VSCode
If you are using Visual Studio Code you can install the Live Server extension which provides a local web server enviroment.
Node.js
Alternatively, if you demand a more responsive setup and already use nodejs...
Install http-server by typing npm install -g http-server
Change into your working directory, where yoursome.html lives
Start your http server by issuing http-server -c-1
This spins up a Node.js httpd which serves the files in your directory as static files accessible from http://localhost:8080
Ruby
If your preferred language is Ruby ... the Ruby Gods say this works as well:
ruby -run -e httpd . -p 8080
PHP
Of course PHP also has its solution.
php -S localhost:8000
In Chrome you can use this flag:
--allow-file-access-from-files
Read more here.
Ran in to this today.
I wrote some code that looked like this:
app.controller('ctrlr', function($scope, $http){
$http.get('localhost:3000').success(function(data) {
$scope.stuff = data;
});
});
...but it should've looked like this:
app.controller('ctrlr', function($scope, $http){
$http.get('http://localhost:3000').success(function(data) {
$scope.stuff = data;
});
});
The only difference was the lack of http:// in the second snippet of code.
Just wanted to put that out there in case there are others with a similar issue.
Just change the url to http://localhost instead of localhost. If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome. That will fix the issue.
I'm going to list 3 different approaches to solve this issue:
Using a very lightweight npm package: Install live-server using npm install -g live-server. Then, go to that directory open the terminal and type live-server and hit enter, page will be served at localhost:8080. BONUS: It also supports hot reloading by default.
Using a lightweight Google Chrome app developed by Google: Install the app, then go to the apps tab in Chrome and open the app. In the app point it to the right folder. Your page will be served!
Modifying Chrome shortcut in windows: Create a Chrome browser's shortcut. Right-click on the icon and open properties. In properties, edit target to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession" and save. Then using Chrome open the page using ctrl+o. NOTE: Do NOT use this shortcut for regular browsing.
Note: Use http:// like http://localhost:8080 in case you face error.
Use http:// or https:// to create url
error: localhost:8080
solution: http://localhost:8080
In an Android app — for example, to allow JavaScript to have access to assets via file:///android_asset/ — use setAllowFileAccessFromFileURLs(true) on the WebSettings that you get from calling getSettings() on the WebView.
fastest way for me was:
for windows users run your file on Firefox problem solved, or
if you want to use chrome easiest way for me was to install Python 3 then from command prompt run command python -m http.server then go to http://localhost:8000/ then navigate to your files
python -m http.server
Easy solution for whom using VS Code
I've been getting this error for a while. Most of the answers works. But I found a different solution. If you don't want to deal with node.js or any other solution in here and you are working with an HTML file (calling functions from another js file or fetch json api's) try to use Live Server extension.
It allows you to open a live server easily. And because of it creates localhost server, the problem is resolving. You can simply start the localhost by open a HTML file and right-click on the editor and click on Open with Live Server.
It basically load the files using http://localhost/index.html instead of using file://....
EDIT
It is not necessary to have a .html file. You can start the Live Server with shortcuts.
Hit (alt+L, alt+O) to Open the Server and (alt+L, alt+C) to Stop the server. [On MAC, cmd+L, cmd+O and cmd+L, cmd+C]
Hope it will help someone :)
If you use old version of Mozilla Firefox (pre-2019), it will work as expected without any issues;
P.S. Surprisingly, old versions of Internet Explorer & Edge work absolutely fine too.
For those on Windows without Python or Node.js, there is still a lightweight solution: Mongoose.
All you do is drag the executable to wherever the root of the server should be, and run it. An icon will appear in the taskbar and it'll navigate to the server in the default browser.
Also, Z-WAMP is a 100% portable WAMP that runs in a single folder, it's awesome. That's an option if you need a quick PHP and MySQL server. Though it hasn't been updated since 2013. A modern alternative would be Laragon or WinNMP. I haven't tested them, but they are portable and worth mentioning.
Also, if you only want the absolute basics (HTML+JS), here's a tiny PowerShell script that doesn't need anything to be installed or downloaded:
$Srv = New-Object Net.HttpListener;
$Srv.Prefixes.Add("http://localhost:8080/");
$Srv.Start();
Start-Process "http://localhost:8080/index.html";
While($Srv.IsListening) {
$Ctx = $Srv.GetContext();
$Buf = [System.IO.File]::OpenRead((Join-Path $Pwd($Ctx.Request.RawUrl)));
$Ctx.Response.ContentLength64 = $Buf.Length;
$Ctx.Response.Headers.Add("Content-Type", "text/html");
$Buf.CopyTo($Ctx.Response.OutputStream);
$Buf.Close();
$Ctx.Response.Close();
};
This method is very barebones, it cannot show directories or other fancy stuff. But it handles these CORS errors just fine.
Save the script as server.ps1 and run in the root of your project. It will launch index.html in the directory it is placed in.
I suspect it's already mentioned in some of the answers, but I'll slightly modify this to have complete working answer (easier to find and use).
Go to: https://nodejs.org/en/download/. Install nodejs.
Install http-server by running command from command prompt npm install -g http-server.
Change into your working directory, where index.html/yoursome.html resides.
Start your http server by running command http-server -c-1
Open web browser to http://localhost:8080
or http://localhost:8080/yoursome.html - depending on your html filename.
I was getting this exact error when loading an HTML file on the browser that was using a json file from the local directory. In my case, I was able to solve this by creating a simple node server that allowed to server static content. I left the code for this at this other answer.
It simply says that the application should be run on a web server. I had the same problem with chrome, I started tomcat and moved my application there, and it worked.
I suggest you use a mini-server to run these kind of applications on localhost (if you are not using some inbuilt server).
Here's one that is very simple to setup and run:
https://www.npmjs.com/package/tiny-server
Experienced this when I downloaded a page for offline view.
I just had to remove the integrity="*****" and crossorigin="anonymous" attributes from all <link> and <script> tags
If you insist on running the .html file locally and not serving it with a webserver, you can prevent those cross origin requests from happening in the first place by making the problematic resources available inline.
I had this problem when trying to to serve .js files through file://. My solution was to update my build script to replace <script src="..."> tags with <script>...</script>.
Here's a gulp approach for doing that:
1.
run npm install --save-dev to packages gulp, gulp-inline and del.
2.
After creating a gulpfile.js to the root directory, add the following code (just change the file paths for whatever suits you):
let gulp = require('gulp');
let inline = require('gulp-inline');
let del = require('del');
gulp.task('inline', function (done) {
gulp.src('dist/index.html')
.pipe(inline({
base: 'dist/',
disabledTypes: 'css, svg, img'
}))
.pipe(gulp.dest('dist/').on('finish', function(){
done()
}));
});
gulp.task('clean', function (done) {
del(['dist/*.js'])
done()
});
gulp.task('bundle-for-local', gulp.series('inline', 'clean'))
Either run gulp bundle-for-local or update your build script to run it automatically.
You can see the detailed problem and solution for my case here.
For all y'all on MacOS... setup a simple LaunchAgent to enable these glamorous capabilities in your own copy of Chrome...
Save a plist, named whatever (launch.chrome.dev.mode.plist, for example) in ~/Library/LaunchAgents with similar content to...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>launch.chrome.dev.mode</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/Google Chrome.app/Contents/MacOS/Google Chrome</string>
<string>-allow-file-access-from-files</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
It should launch at startup.. but you can force it to do so at any time with the terminal command
launchctl load -w ~/Library/LaunchAgents/launch.chrome.dev.mode.plist
TADA! 😎 💁🏻 🙊 🙏🏾
Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"
npm install http-server -g
http-server [path] [options]
Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.
er. I just found some official words "Attempting to load unbuilt, remote AMD modules that use the dojo/text plugin will fail due to cross-origin security restrictions. (Built versions of AMD modules are unaffected because the calls to dojo/text are eliminated by the build system.)" https://dojotoolkit.org/documentation/tutorials/1.10/cdn/
One way it worked loading local files is using them with in the project folder instead of outside your project folder. Create one folder under your project example files similar to the way we create for images and replace the section where using complete local path other than project path and use relative url of file under project folder .
It worked for me
Install local webserver for java e.g Tomcat,for php you can use lamp etc
Drop the json file in the public accessible app server directory
Start the app server,and you should be able to access the file from localhost
For Linux Python users:
import webbrowser
browser = webbrowser.get('google-chrome --allow-file-access-from-files %s')
browser.open(url)
url should be like:
createUserURL = "http://www.localhost:3000/api/angular/users"
instead of:
createUserURL = "localhost:3000/api/angular/users"
Many problem for this, with my problem is missing '/' example:
jquery-1.10.2.js:8720 XMLHttpRequest cannot load http://localhost:xxxProduct/getList_tagLabels/
It's must be: http://localhost:xxx/Product/getList_tagLabels/
I hope this help for who meet this problem.
I have also been able to recreate this error message when using an anchor tag with the following href:
Example a tag
In my case an a tag was being used to get the 'Pointer Cursor' and the event was actually controlled by some jQuery on click event. I removed the href and added a class that applies:
cursor:pointer;
cordova achieve this. I still can not figure out how cordova did. It does not even go through shouldInterceptRequest.
Later I found out that the key to load any file from local is: myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
And when you want to access any http resource, the webview will do checking with OPTIONS method, which you can grant the access through WebViewClient.shouldInterceptRequest by return a response, and for the following GET/POST method, you can just return null.
If you are searching for a solution for Firebase Hosting, you can run the
firebase serve --only hosting command from the Firebase CLI
That's what I came here for, so I thought I'd just leave it here to help like ones.
If your using VS code just trying loading a live server in there. fixed my problem immediately.

Rapid chrome extension development [duplicate]

I'd like for my chrome extension to reload every time I save a file in the extension folder, without having to explicitly click "reload" in chrome://extensions/. Is this possible?
Edit: I'm aware I can update the interval at which Chrome reloads extensions, which is a half-way solution, but I'd rather either making my editor (emacs or textmate) trigger on-save a reload or asking Chrome to monitor the directory for changes.
You can use "Extensions Reloader" for Chrome:
Reloads all unpacked extensions using the extension's toolbar button or by browsing to "http://reload.extensions"
If you've ever developed a Chrome extension, you might have wanted to
automate the process of reloading your unpacked extension without the
need of going through the extensions page.
"Extensions Reloader" allows you to reload all unpacked extensions
using 2 ways:
1 - The extension's toolbar button.
2 - Browsing to "http://reload.extensions".
The toolbar icon will reload unpacked extensions using a single click.
The "reload by browsing" is intended for automating the reload process
using "post build" scripts - just add a browse to
"http://reload.extensions" using Chrome to your script, and you'll
have a refreshed Chrome window.
Update: As of January 14, 2015, the extension is open-sourced and available on GitHub.
Update: I have added an options page, so that you don't have to manually find and edit the extension's ID any more. CRX and source code are at: https://github.com/Rob--W/Chrome-Extension-Reloader
Update 2: Added shortcut (see my repository on Github).
The original code, which includes the basic functionality is shown below.
Create an extension, and use the Browser Action method in conjunction with the chrome.extension.management API to reload your unpacked extension.
The code below adds a button to Chrome, which will reload an extension upon click.
manifest.json
{
"name": "Chrome Extension Reloader",
"version": "1.0",
"manifest_version": 2,
"background": {"scripts": ["bg.js"] },
"browser_action": {
"default_icon": "icon48.png",
"default_title": "Reload extension"
},
"permissions": ["management"]
}
bg.js
var id = "<extension_id here>";
function reloadExtension(id) {
chrome.management.setEnabled(id, false, function() {
chrome.management.setEnabled(id, true);
});
}
chrome.browserAction.onClicked.addListener(function(tab) {
reloadExtension(id);
});
icon48.png: Pick any nice 48x48 icon, for example:
I've made a simple embeddable script doing hot reload:
https://github.com/xpl/crx-hotreload
It watches for file changes in an extension's directory. When a change detected, it reloads the extension and refreshes the active tab (to re-trigger updated content scripts).
Works by checking timestamps of files
Supports nested directories
Automatically disables itself in the production configuration
in any function or event
chrome.runtime.reload();
will reload your extension (docs). You also need to change the manifest.json file, adding:
...
"permissions": [ "management" , ...]
...
I am using a shortcut to reload. I don't want to reload all the time when I save a file
So my approach is lightweight, and you can leave the reload function in
manifest.json
{
...
"background": {
"scripts": [
"src/bg/background.js"
],
"persistent": true
},
"commands": {
"Ctrl+M": {
"suggested_key": {
"default": "Ctrl+M",
"mac": "Command+M"
},
"description": "Ctrl+M."
}
},
...
}
src/bg/background.js
chrome.commands.onCommand.addListener((shortcut) => {
console.log('lets reload');
console.log(shortcut);
if(shortcut.includes("+M")) {
chrome.runtime.reload();
}
})
Now press Ctrl + M in the chrome browser to reload
Another solution would be to create custom livereload script (extension-reload.js):
// Reload client for Chrome Apps & Extensions.
// The reload client has a compatibility with livereload.
// WARNING: only supports reload command.
var LIVERELOAD_HOST = 'localhost:';
var LIVERELOAD_PORT = 35729;
var connection = new WebSocket('ws://' + LIVERELOAD_HOST + LIVERELOAD_PORT + '/livereload');
connection.onerror = function (error) {
console.log('reload connection got error:', error);
};
connection.onmessage = function (e) {
if (e.data) {
var data = JSON.parse(e.data);
if (data && data.command === 'reload') {
chrome.runtime.reload();
}
}
};
This script connects to the livereload server using websockets. Then, it will issue a chrome.runtime.reload() call upon reload message from livereload. The next step would be to add this script to run as background script in your manifest.json, and voila!
Note: this is not my solution. I'm just posting it. I found it in the generated code of Chrome Extension generator (Great tool!). I'm posting this here because it might help.
TL;DR
Create a WebSocket server that dispatches a message to a background script that can handle the update. If you are using webpack and don't plan to do it yourself, webpack-run-chrome-extension can help.
Answer
You can create a WebSocket server to communicate with the extension as a WebSocket client (via window object). The extension would then listen for file changes by attaching the WebSocket server to some listener mechanism (like webpack devServer).
Did the file change? Set the server to dispatch a message to the extension asking for updates (broadcasting the ws message to the client(s)). The extension then reloads, replies with "ok, reloaded" and keeps listening for new changes.
Plan
Set up a WebSocket server (to dispatch update requests)
Find a service that can tell you when did the files change (webpack/other bundler software)
When an update happens, dispatch a message to client requesting updates
Set up a WebSocket client (to receive update requests)
Reload the extension
How
For the WebSocket server, use ws. For file changes, use some listener/hook (like webpack's watchRun hook). For the client part, native WebSocket. The extension could then attach the WebSocket client on a background script for keeping sync persistent between the server (hosted by webpack) and the client (the script attached in the extension background).
Now, to make the extension reload itself, you can either call chrome.runtime.reload() in it each time the upload request message comes from the server, or even create a "reloader extension" that would do that for you, using chrome.management.setEnabled() (requires "permissions": [ "management" ] in manifest).
In the ideal scenario, tools like webpack-dev-server or any other web server software could offer support for chrome-extension URLs natively. Until that happens, having a server to proxy file changes to your extension seems to be the best option so far.
Available open-source alternative
If you are using webpack and don't want to create it all yourself, I made webpack-run-chrome-extension, which does what I planned above.
Chrome Extensions have a permission system that it wouldn't allow it (some people in SO had the same problem as you), so requesting them to "add this feature" is not going to work IMO. There's a mail from Chromium Extensions Google Groups with a proposed solution (theory) using chrome.extension.getViews(), but is not guaranteed to work either.
If it was possible to add to the manifest.json some Chrome internal pages like chrome://extensions/, it would be possible to create a plugin that would interact to the Reload anchor, and, using an external program like XRefresh (a Firefox Plugin - there's a Chrome version using Ruby and WebSocket), you would achieve just what you need:
XRefresh is a browser plugin which
will refresh current web page due to
file change in selected folders. This
makes it possible to do live page
editing with your favorite HTML/CSS
editor.
It's not possible to do it, but I think you can use this same concept in a different way.
You could try to find third-party solutions instead that, after seeing modifications in a file (I don't know emacs neither Textmate, but in Emacs it would be possible to bind an app call within a "save file" action), just clicks in an specific coordinate of an specific application: in this case it's the Reload anchor from your extension in development (you leave a Chrome windows opened just for this reload).
(Crazy as hell but it may work)
Here's a function that you can use to watch files for changes, and reload if changes are detected. It works by polling them via AJAX, and reloading via window.location.reload(). I suppose you shouldn't use this in a distribution package.
function reloadOnChange(url, checkIntervalMS) {
if (!window.__watchedFiles) {
window.__watchedFiles = {};
}
(function() {
var self = arguments.callee;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (__watchedFiles[url] &&
__watchedFiles[url] != xhr.responseText) {
window.location.reload();
} else {
__watchedFiles[url] = xhr.responseText
window.setTimeout(self, checkIntervalMS || 1000);
}
}
};
xhr.open("GET", url, true);
xhr.send();
})();
}
reloadOnChange(chrome.extension.getURL('/myscript.js'));
The great guys at mozilla just released a new https://github.com/mozilla/web-ext that you can use to launch web-ext run --target chromium
Maybe I'm a little late to the party, but I've solved it for me by creating https://chrome.google.com/webstore/detail/chrome-unpacked-extension/fddfkmklefkhanofhlohnkemejcbamln
It works by reloading chrome://extensions page, whenever file.change events are incoming via websockets.
A Gulp-based example of how to emit file.change event upon file changes in an extension folder can be found here: https://github.com/robin-drexler/chrome-extension-auto-reload-watcher
Why reloading the entire tab instead of just using the extensions management api to reload/re-enable extensions? Currently disabling and enabling extensions again causes any open inspection window (console log etc.) to close, which I found to be too annoying during active development.
There's an automatic reload plugin if you're developing using webpack:
https://github.com/rubenspgcavalcante/webpack-chrome-extension-reloader
const ChromeExtensionReloader = require('webpack-chrome-extension-reloader');
plugins: [
new ChromeExtensionReloader()
]
Also comes with a CLI tool if you don't want to modify webpack.config.js:
npx wcer
Note: an (empty) background script is required even if you don't need it because that's where it injects reload code.
Maybe a bit late answer but I think crxreload might work for you. It's my result of trying to have a reload-on-save workflow while developing.
Use npm init to create a package.json in directory root, then
npm install --save-dev gulp-open && npm install -g gulp
then create a gulpfile.js
which looks like:
/* File: gulpfile.js */
// grab our gulp packages
var gulp = require('gulp'),
open = require('gulp-open');
// create a default task and just log a message
gulp.task('default', ['watch']);
// configure which files to watch and what tasks to use on file changes
gulp.task('watch', function() {
gulp.watch('extensionData/userCode/**/*.js', ['uri']);
});
gulp.task('uri', function(){
gulp.src(__filename)
.pipe(open({uri: "http://reload.extensions"}));
});
This works for me developing with CrossRider, you might watch to change the path you watch the files at, also assuming you have npm and node installed.
Your content files such has html and manifest files are not changeable without installation of the extension, but I do believe that the JavaScript files are dynamically loaded until the extension has been packed.
I know this because of a current project im working on via the Chrome Extensions API, and seems to load every-time i refresh a page.
Disclaimer: I developed this extension myself.
Clerc - for Chrome Live Extension Reloading Client
Connect to a LiveReload compatible server to automatically reload your extension every time you save.
Bonus: with a little extra work on your part, you can also automatically reload the webpages that your extension alters.
Most webpage developers use a build system with some sort of watcher that automatically builds their files and restarts their server and reloads the website.
Developing extensions shouldn't need to be that different. Clerc brings this same automation to Chrome devs. Set up a build system with a LiveReload server, and Clerc will listen for reload events to refresh your extension.
The only big gotcha is changes to the manifest.json. Any tiny typos in the manifest will probably cause further reload attempts to fail, and you will be stuck uninstalling/reinstalling your extension to get your changes loading again.
Clerc forwards the complete reload message to your extension after it reloads, so you can optionally use the provided message to trigger further refresh steps.
Thanks to #GmonC and #Arik and some spare time, I managet to get this working. I have had to change two files to make this work.
(1) Install LiveReload and Chrome Extension for that application.
This will call some script on file change.
(2) Open <LiveReloadInstallDir>\Bundled\backend\res\livereload.js
(3) change line #509 to
this.window.location.href = "http://reload.extensions";
(4) Now install another extension Extensions Reloader which has useful link handler that reload all development extensions on navigating to "http://reload.extensions"
(5) Now change that extension's background.min.js in this way
if((d.installType=="development")&&(d.enabled==true)&&(d.name!="Extensions Reloader"))
replace with
if((d.installType=="development")&&(d.enabled==true)&&(d.name!="Extensions Reloader")&&(d.name!="LiveReload"))
Open LiveReload application, hide Extension Reloader button and activate LiveReload extension by clicking on button in toolbar, you will now reload page and extensions on each file change while using all other goodies from LiveReload (css reload, image reload etc.)
Only bad thing about this is that you will have to repeat procedure of changing scripts on every extension update. To avoid updates, add extension as unpacked.
When I'll have more time to mess around with this, I probably will create extension that eliminates need for both of these extensions.
Untill then, I'm working on my extension Projext Axeman
Just found a newish grunt based project that provides bootstrapping, scaffolding, some automated pre-processing faculty, as well as auto-reloading (no interaction needed).
Bootstrap Your Chrome Extension from Websecurify
I want to reload (update) my extensions overnight, this is what I use in background.js:
var d = new Date();
var n = d.getHours();
var untilnight = (n == 0) ? 24*3600000 : (24-n)*3600000;
// refresh after 24 hours if hour = 0 else
// refresh after 24-n hours (that will always be somewhere between 0 and 1 AM)
setTimeout(function() {
location.reload();
}, untilnight);
Regards,
Peter
I primarily develop in Firefox, where web-ext run automatically reloads the extension after files change. Then once it's ready, I do a final round of testing in Chrome to make sure there aren't any issues that didn't show up in Firefox.
If you want to develop primarily in Chrome, though, and don't want to install any 3rd party extensions, then another option is to create a test.html file in the extension's folder, and add a bunch of SSCCE's to it. That file then uses a normal <script> tag to inject the extension script.
You could use that for 95% of testing, and then manually reload the extension when you want to test it on live sites.
That doesn't identically reproduce the environment that an extension runs in, but it's good enough for many simple things.
MAC ONLY
Using Extensions Reloader:
Using Typescript
Add the watcher of your to your project: yarn add tsc-watch
Add command to scripts to package.json
...
"scripts": {
"dev": "tsc-watch --onSuccess \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
},
...
Run script yarn dev
Using JavaScript
Add the watcher of your to your project: yarn add watch-cli
Add command to scripts to package.json
...
"scripts": {
"dev": "watch -p \"**/*.js\" -c \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
},
...
Run script yarn dev
Bonus: Turn on 'reload current tab' in Extensions Reloader options, so it reloads after a change was made:
I've forked LiveJS to allow for live reloading of Packaged Apps. Just include the file in your app and every time you save a file the app will autoreload.
As mentioned in the docs: the following command line will reload an app
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --load-and-launch-app=[path to the app ]
so I just created a shell script and called that file from gulp. Super simple:
var exec = require('child_process').exec;
gulp.task('reload-chrome-build',function(cb){
console.log("reload");
var cmd="./reloadchrome.sh"
exec(cmd,function (err, stdout, stderr) {
console.log("done: "+stdout);
cb(err);
}
);});
run your necessary watch commands on scripts and call the reload task when you want to. Clean, simple.
This is where software such as AutoIt or alternatives shine. The key is writing a script which emulates your current testing phase. Get used to using at least one of them as many technologies do not come with clear workflow/testing paths.
Run("c:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
WinWaitActive("New Tab - Google Chrome")
Send("^l")
Send("chrome://extensions{ENTER}")
WinWaitActive("Extensions - Google Chrome")
Send("{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}")
Send("{ENTER}")
WinWaitActive("Extensions - Google Chrome")
Send("{TAB}{TAB}")
Send("{ENTER}")
WinWaitActive("Developer Tools")
Send("^`")
Obviously you change the code to suit your testing/iterating needs. Make sure tab clicks are true to where the anchor tag is in the chrome://extensions site. You could also use relative to window mouse movements and other such macros.
I would add the script to Vim in a way similar to this:
map <leader>A :w<CR>:!{input autoit loader exe here} "{input script location here}"<CR>
This means that when I'm in Vim I press the button above ENTER (usually responsible for: | and \) known as the leader button and follow it with a capital 'A' and it saves and begins my testing phase script.
Please make sure to fill in the {input...} sections in the above Vim/hotkey script appropriately.
Many editors will allow you to do something similar with hotkeys.
Alternatives to AutoIt can be found here.
For Windows: AutoHotkey
For Linux: xdotool, xbindkeys
For Mac: Automator
If you have a Mac, ¡the easiest way is with Alfred App!
Just get Alfred App with Powerpack, then add the workflow provided in the link below and customise the hotkey you want (I like to use ⌘ + ⌥ + R). That's all.
Now, every time you use the hotkey, Google Chrome will reload, no matter which application you're at that moment.
If you want to use other browser, open the AppleScript inside Alfred Preferences Workflows and replace "Google Chrome" with "Firefox", "Safari", ...
I also will show here the content of the /usr/bin/osascript script used in the ReloadChrome.alfredworkflow file so you can see what it is doing.
tell application "Google Chrome"
activate
delay 0.5
tell application "System Events" to keystroke "r" using command down
delay 0.5
tell application "System Events" to keystroke tab using command down
end tell
The workflow file is ReloadChrome.alfredworkflow.
The author recommended the next version of that webpack plugin: https://github.com/rubenspgcavalcante/webpack-extension-reloader. It works very well for me.
Yes,you can do it indirectly! Here is my solution.
In manifest.json
{
"name": "",
"version": "1.0.0",
"description": "",
"content_scripts":[{
"run_at":"document_end",
"matches":["http://*/*"],
"js":["/scripts/inject.js"]
}]
}
In inject.js
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'Your_Scripts';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(script, s);
})();
Your injected script can inject other script from any location.
Another benefit from this technic is that you can just ignore the limitation of isolated world. see content script execution environment
BROWSER-SYNC
Using the amazing Browser-Sync
update browsers (any) when source code changes (HTML, CSS, images, etc.)
support Windows, MacOS and Linux
you could even watch your code updates (live) using your mobile devices
Instalation on MacOS (view their help to install on other OS)
Install NVM, so you can try any Node version
brew install nvm # install a Node version manager
nvm ls-remote # list available Node versions
nvm install v10.13.0 # install one of them
npm install -g browser-sync # install Browser-Sync
How to use browser-sync for static sites
Let's see two examples:
browser-sync start --server --files . --host YOUR_IP_HERE --port 9000
browser-sync start --server --files $(ack --type-add=web:ext:htm,html,xhtml,js,css --web -f | tr \\n \ ) --host $(ipconfig getifaddr en0) --port 9000
The --server option allow you to run a local server anywhere you are in your terminal and --files let you specify which files will be tracked for changes. I prefer to be more specific for the tracked files, so in the second example I use ack for listing specific file extensions (is important that those files do not have filenames with spaces) and also useipconfig to find my current IP on MacOS.
How to use browser-sync for dynamic sites
In case you are using PHP, Rails, etc., you already have a running server, but it doesn't refresh automatically when you make changes to your code. So you need to use the --proxy switch to let browser-sync know where is the host for that server.
browser-sync start --files $(ack --type-add=rails:ext:rb,erb,js,css,sass,scss,coffee --rails -f | tr \\n \ ) --proxy 192.168.33.12:3000 --host $(ipconfig getifaddr en0) --port 9000 --no-notify --no-open
In the above example, I already have a Rails app running on my browser on 192.168.33.12:3000. It really runs on a VM using a Vagrant box, but I could access the virtual machine using port 3000 on that host. I like --no-notify to stop browser-sync sending me a notification alert on the browser every time I change my code and --no-open to stop browser-sync behavior that immediately loads a browser tab when the server start.
IMPORTANT: Just in case you're using Rails, avoid using Turbolinks on development, otherwise you will not be able click on your links while using the --proxy option.
Hope it would be useful to someone. I've tried many tricks to refresh the browser (even an old post I've submitted on this StackOverflow question using AlfredApp time ago), but this is really the way to go; no more hacks, it just flows.
CREDIT: Start a local live reload web server with one command
It can't be done directly. Sorry.
If you would like to see it as a feature you can request it at http://crbug.com/new

Cross origin requests are only supported for HTTP but it's not cross-domain

I'm using this code to make an AJAX request:
$("#userBarSignup").click(function(){
$.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
{/*params*/},
function(response){
$("#signup").html("TEST");
$("#signup").html(response);
},
"html");
But from the Google Chrome JavaScript console I keep receiving this error:
XMLHttpRequest cannot load
file:///C:/xampp/htdocs/webname/resources/templates/signup.php. Cross
origin requests are only supported for HTTP.
The problem is that the signup.php file is hosted on my local web server that's where all the website is run from so it's not cross-domain.
How can I solve this problem?
I've had luck starting chrome with the following switch:
--allow-file-access-from-files
On os x try (re-type the dashes if you copy paste):
open -a 'Google Chrome' --args -allow-file-access-from-files
On other *nix run (not tested)
google-chrome --allow-file-access-from-files
or on windows edit the properties of the chrome shortcut and add the switch, e.g.
C:\ ... \Application\chrome.exe --allow-file-access-from-files
to the end of the "target" path
If you’re working on a little front-end project and want to test it locally, you’d typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they’re placed in your local directory, you might see warnings like this:
XMLHttpRequest cannot load file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP.
Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you’d need to mount a webserver to run your project there.
This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you’re running several other projects), node.js with express, a Ruby server, etc. or simply modifying your browser settings.
However there’s a simpler and lightweight solution for the lazy ones. You can use Python’s SimpleHTTPServer. It comes already bundled with python so you don’t need to install or configure anything at all!
So cd to your project directory, for instance
1
cd /home/erick/mysuperproject
and then simply use
1
python -m SimpleHTTPServer
And that’s it, you’ll see this message in your terminal
1
Serving HTTP on 0.0.0.0 port 8000 ...
So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I’m in a rush to test a new library or work out a new idea.
EDIT:
In Python 3+, SimpleHTTPServer has been replaced with http.server. So In Python 3.3, for example, the following command is equivalent:
python -m http.server 8000
You need to actually run a webserver, and make the get request to a URI on that server, rather than making the get request to a file; e.g. change the line:
$.get("C:/xampp/htdocs/webname/resources/templates/signup.php",
to read something like:
$.get("http://localhost/resources/templates/signup.php",
and the initial request page needs to be made over http as well.
I was getting the same error while trying to load simply HTML files that used JSON data to populate the page, so I used used node.js and express to solve the problem. If you do not have node installed, you need to install node first.
Install express
npm install express
Create a server.js file in the root folder of your project, in my case one folder above the files I wanted to server
Put something like the following in the server.js file and read about this on the express gihub site:
var express = require('express');
var app = express();
var path = require('path');
// __dirname will use the current path from where you run this file
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, '/FOLDERTOHTMLFILESTOSERVER')));
app.listen(8000);
console.log('Listening on port 8000');
After you've saved server.js, you can run the server using:
node server.js
Go to http://localhost:8000/FILENAME and you should see the HTML file you were trying to load
If you have nodejs installed, you can download and install the server using command line:
npm install -g http-server
Change directories to the directory where you want to serve files from:
$ cd ~/projects/angular/current_project
Run the server:
$ http-server
which will produce the message Starting up http-server, serving on:
Available on:
http://your_ip:8080 and
http://127.0.0.1:8080
That allows you to use urls in your browser like
http://your_ip:8080/index.html
It works best this way. Make sure that both files are on the server. When calling the html page, make use of the web address like: http:://localhost/myhtmlfile.html, and not, C::///users/myhtmlfile.html. Make usre as well that the url passed to the json is a web address as denoted below:
$(function(){
$('#typeahead').typeahead({
source: function(query, process){
$.ajax({
url: 'http://localhost:2222/bootstrap/source.php',
type: 'POST',
data: 'query=' +query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
});
}
});
});
REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
change chromeLocation path with yours.
save above as .bat file.
drag drop you file on the batch file you created. (chrome does give restore pages
option though so if you have pages open just hit restore and it will work).
You can also start a server without python using php interpreter.
E.g:
cd /your/path/to/website/root
php -S localhost:8000
This can be useful if you want an alternative to npm, as php utility comes preinstalled on some OS' (including Mac).
For all python users:
Simply go to your destination folder in the terminal.
cd projectFoder
then start HTTP server
For Python3+:
python -m http.server 8000
Serving HTTP on :: port 8000 (http://[::]:8000/) ...
go to your link: http://0.0.0.0:8000/
Enjoy :)

Categories