After I press ctrl + c to interrupt a running browser-sync start, my browsers opened by browser-sync are still open.
After repeating this ctrl + c and browser-sync start process a few times (happens a lot while developing), my browsers can have lots of tabs opening the same site.
And if you use the built-in server offered by browser-sync, leaving these browsers open doesn't really make sense since the server is gone too.
I wonder if there could be an option to close the browser windows opened by browser-sync after it exits?
You can add a middleware that closes windows opened by browser-sync:
// middleware.js
(function ($window, $document, bs) {
var socket = bs.socket;
socket.on("disconnect", function (client) {
window.close();
});
})(window, document, ___browserSync___);
var bsCloser = fs.readFileSync('path/to/middleware.js', 'utf-8');
browserSync.use({
plugin: function() {},
hooks: {
'client:js': bsCloser
}
});
What I noticed using this was that it only works when the URL stays unchanged. If you follow a link, the ability is lost. This is due to browser restrictions preventing programmatic closing of windows that are not opened by the script.
Unfortunately is is not possible - (other than what @Nirazul) mentioned above.
I think it's also possible to add the middleware (to close the browser window) as a one-liner like this:
var browserSync = require('browser-sync');
browserSync.use({
plugin: function() {},
hooks: {
'client:js': '(function (bs) {bs.socket.on("disconnect", function (client) { window.close(); });})(___browserSync___);'
}
});
browserSync.create();
Most helpful comment
I think it's also possible to add the middleware (to close the browser window) as a one-liner like this: