Browser-sync: Option to close the opened browsers once browser-sync exits?

Created on 28 Jul 2015  路  3Comments  路  Source: BrowserSync/browser-sync

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?

Most helpful comment

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();

All 3 comments

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();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

w88975 picture w88975  路  3Comments

ngryman picture ngryman  路  3Comments

ericmorand picture ericmorand  路  3Comments

npearson72 picture npearson72  路  3Comments

arve0 picture arve0  路  4Comments