How do I auto-reload a Chrome extension I'm developing? - javascript

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

Related

Can't requestQuota for files since Chrome 86

I recently tried to update one of my former webapp project in which I need to download files from a server and store them on the device (to access it later).
In order to achieve this I use the navigator.persistentStorage (or navigator.webkitPersistentStorage) and its requestQuota function as seen in https://developer.mozilla.org/en-US/docs/Web/API/LocalFileSystem#using_persistent_storage
The issue is that, when I test my application locally (accessing the index.html via file:///) the requestQuota triggers the "Do you want to allow" chrome popup but when I select "Yes" I get a failure with following DOMError :
{
message: "The implementation did not support the requested type of object or operation."
name: "NotSupportedError"
}
On the other hand, when I access the application deployed on its distant server everything works like a charm.
Beeing aware of the restrictions of the file API in local (https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction#file), I ran thoses tests with a custom chrome :
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --ssl-version-min=tls1 --allow-file-access-from-files --allow-file-access --disable-web-security --user-data-dir="C:\tmp\chromeDev"
To test it outside of my application environment, I tried the simple line in chrome inspect :
navigator.webkitPersistentStorage.requestQuota(1024*1024,
r => console.log('success'),
e => console.log('failure : ' + e)
);
On a random local index.html openened in chrome (with file:///) --> "failure".
On a random website (with https://) --> "success".
I downgraded my Chrome and found out all of this problem only occurs since Chrome 86.
Ideally I should upgrade my application to use IndexedDb API, but in the short run a fix or workaround would be quite welcome :)
Thx

Executing a batch file via JavaScript [duplicate]

Is it possible to run bat/executable file using html5 button event? In IE its achievable using Shell object if I am not wrong.
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.
Here's what I did. I wanted a HTML page setup on our network so I wouldn't have to navigate to various folders to install or upgrade our apps. So what I did was setup a .bat file on our "shared" drive that everyone has access to, in that .bat file I had this code:
start /d "\\server\Software\" setup.exe
The HTML code was:
<input type="button" value="Launch Installer" onclick="window.open('file:///S:Test/Test.bat')" />
(make sure your slashes are correct, I had them the other way and it didn't work)
I preferred to launch the EXE directly but that wasn't possible, but the .bat file allowed me around that. Wish it worked in FF or Chrome, but only IE.
It is possible when the page itself is opened via a file:/// path.
<button onclick="window.open('file:///C:/Windows/notepad.exe')">
Launch notepad
</button>
However, the moment you put it on a webserver (even if you access it via http://localhost/), you will get an error:
Error: Access to 'file:///C:/Windows/notepad.exe' from script denied
You can do it on Internet explorer with OCX component and on chrome browser using a chrome extension
chrome document
in any case need additional settings on the client system!
Important part of chrome extension source:
var port = chrome.runtime.connectNative("your.app.id");
port.onMessage.addListener(onNativeMessage);
port.onDisconnect.addListener(onDisconnected);
port.postMessage("send some data to STDIO");
permission file:
{
"name": "your.app.id",
"description": "Name of your extension",
"path": "myapp.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://IDOFYOUREXTENSION_lokldaeplkmh/"
]
}
and windows registry settings:
HKEY_CURRENT_USER\Software\Google\Chrome\NativeMessagingHosts\your.app.id
REG_EXPAND_SZ : c:\permissionsettings.json
You can not run/execute an .exe file that is in the users local machine or through a site. The user must first download the exe file and then run the executable file. So there is no possible way
The following code works only when the EXE is Present in the User's Machine.
<a href = "C:\folder_name\program.exe">

How to automatically close webpage using javascript?

I have found many questions like mine in different forums, but I couldn't find an answer that actually helps to solve my problem in any of them.
Basically, what I want is to open an URL through command prompt, it will open the browser, processes a webpage, and then I would like it to automatically close.
Why do I need this?
I have an application that runs on IIS. There are some routines I need to run everyday in my application. I can simply kick of these routines by running an URL similar to the showed below:
http://myapplication.com/DoStuff.aspx?
The Problem is that this is totally manual.
I was wondering if I could create a batch file calling my URL "start http://myapplication.com/DoStuff.aspx?", and then I could create a task on Windows to run that batch file everyday. That works for me except that the browser will not close automatically.
What I mean is, I could try it, but at the end of a week, I would have at least 5 windows opened.
What I have tried:
I have tried to solve it by using javascript, but I always end up getting this message:
scripts may close only the windows that were opened by it
It does not matter the javascript function I create using "window.close()", the windows won't close.
Chrome and Firefox returns that message.
IE let's me try to close the window, but it asks in a popUp if I really want to close it.
What you need is probably a headless browser like PhantomJS (WebKit browser without GUI). I would recommend you to use CasperJS to create scripts even more easily...
Install Phantom and Casper globally on your system and write a minimal automation script like so:
var casper = require('casper').create();
casper.start('http://myapplication.com/DoStuff.aspx');
casper.then(function() {
// Do something here...
});
casper.run();
Set a cron job (or Windows equivalent) to execute the script with the casperjs bin. Normally, it should do the trick...
Using batch files only because I strongly believe you do not need JavaScript to do this.
::start a new browser session at the given url
start iexplore "http://www.google.com"
::wait for whatever process to end if you actually have to wait
timeout 15
::kill the browser process
taskkill /im iexplore.exe /f /t
If it runs on a machine nobody interacts with, and you know the session you log into will be the last session you got out of, then you know the session you're getting into already has IE open. So you could reverse the order of the script and not care much about timing
::kill the browser already opened
taskkill /im iexplore.exe /f /t
::open a new browser session at the given url
start iexplore "http://www.google.com"
::if you have to wait, but don't know how long... leave the browser window open. We'll close it next time we run this batch file anyway.
At *nix you can create a bash script containing
#!/bin/bash
/usr/bin/chromium-browser --user-data-dir="/home/USER/.config/chromium-no-flags" "http://myapplication.com/DoStuff.aspx"
within DoStuff.aspx, use setTimeout() or other function to call window.close() when task is complete
setTimeout(close, 10000)
or
new Promise((resolve, reject) => {
// do asynchronous stuff
resolve(/* value */)
})
.then(close)
.catch(close)
For *indows equivalent of cron see
What is the Windows version of cron?
Windows equivalent to cron?
See also
Close google chrome open in app mode via command line
Open Chrome from command line and wait till it's closed
Close programs from the command line (Windows)
Killing all instances of Chrome on the command-line?

How run a windows console for JavaScript

I would like to have a console window (a command line) on Windows 7 which will allow me to play with JavaScript just like a python console.
Update:
It's important to have a file access from within the console (or script run through it).
You can use Node.js's REPL. To do so follow this steps:
Download and Install Node.js.
Call Node.js from the Start Menu / Start Screen or directly node.exe installation path (e.g C:\Program Files\nodejs\node.exe).
Enjoy!
You may want to add the installation path to your PATH enviroment variable for ease of use.
Note: to leave node.js press Ctrl + C twice.
To access the local files, you will need the File System module. This is an example of usage:
var fs = require("fs");
fs.readFile(
"C:\\test.txt",
function(err, data)
{
if (!err)
console.log(data.toString());
}
);
This will output the contents of the file C:\test.txt to the console.
Note: An unhandled exception will cause node.js to "crash".
You can just use the developer tools.
For example, in Chrome, press F12. This will bring up the developer tools. The last option on the menubar is console. This will allow you to create JS variables and functions and to interact with DOM elements on the current page
It's possible thanks to Mozilla Rhino JavaScript Engine.
To create a console window for JS:
1) Download Mozilla Rhino JavaScript Engine binary.
2) Extract: js.jar.
3) Create a script to run the console window (e.g. rihno_console.bat):
java -cp js.jar org.mozilla.javascript.tools.shell.Main
For more information about usage (for instance, and global functions inside this console) visit the Rhino Shell web page.
Just like I informed another user with the same question as yours who was faced with the same need, check out DeskJS (https://deskjs.wordpress.com). It's a portable Windows console application that lets you run pure JavaScript code and even load any existing JS files. It supports even the basic JS popup boxes implemented in browsers. You can save your commands as JS files that can be run on startup or by dragging-and-dropping them on the app. Plus there's so much more to it like you can create a build system for Sublime Text that can run JS files via cmd, it supports themes for customizing the entire console and snippets which let you save short snippets of JavaScript code for later use. Improvements are still being made on the app together with other native APIs being included. Hope this helps you as it did for me.

Debug Javascript in netbeans 7.4 inside PHP project

I want to debug javascript code inside my php project in netbeans. I have read on several occasions that this should be possible in the new netbeans 7.4 version, for example here and here, but i cannot get it to work. I have installed de debugger connector for chrome and php debugging works just fine but when i try to set a breakpoint in a .js file it says:
unresolved breakpoint,
debugger is not attached to tab with id....
i understand that the link from the netbeans page is for an html 5 application but i thought this debugging would also be enabled in php projects. Am i doing something wrong?
i know i can debug with firebug or chrome itself but i would like to do it all in one place in my netbeans IDE...
thanks in advance
The unresolved breakpoint usually mean that for instance you set it in file that is not loaded in Chrome's tab right now (or for some reason, IDE cannot match URL of JS file and local JS file). The mixed debugging works only in Embdded Browser or in Chrome with NetBeans connector (you can see the usually yellow bar in your page saying "NetBeans connector is debugging this page" and you can debug PHP and JS at the same time.
Have a look here, although it is about Java EE projects, it is very similar to PHP projects
Updated answer:
One issue I remember (and plain Chrome Dev Tools has it as well) is that if you have JavaScript file attached to HTML/PHP with dynamic parameter to prevent browser from caching, e.g. , where "673612" changes each time a file is loaded. If that's your case, try to remove this dynamic attribute. I think that e.g. Sencha or ExtJS use this feature which "breaks" debuggers.
I had a similar problem : javascript breakpoints were broken, while everything else was working fine (for example php breakpoints were okay).
The reason was that in the run configuration properties I changed the Project URL to something that was not the host anymore, but a subfolder managed by a url rewriting rule.
johanvs is correct, but my reputation is not enough to +1.
Suppose a NetBeans project contains many files in different folders:
/var/www/index.html
/var/www/config.html
/usr/doc/readme.txt
/usr/doc/license.txt
Since "index.html" is not in the project root folder but under "/var/www", NetBeans does not know "http://127.0.0.1/index.html" is corresponding to "/var/www/index.html". To solve, verify below settings in NetBeans -> File -> Project Properties:
Sources -> Web Root
"var/www"
Run Configuration -> Project URL
"http://127.0.0.1/"
Run Configuration -> Index File -> Browse
"index.html"
Run Configuration -> Remote Connection -> Manage -> Initial Directory
"/"
Run Configuration -> Upload Directory
(empty)

Categories

Resources