forked from FWeinb/node-webkit-screenshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
85 lines (64 loc) · 1.71 KB
/
browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
var path = require('path');
var spawn = require('win-spawn');
var Promise = require('bluebird');
var server = require('http').createServer();
var io = require('socket.io').listen(server);
var app = path.join(__dirname, 'nw-screenshot');
var nodewebkit = require('nodewebkit').findpath();
var requestId = 0;
var Browser = function(socket){
this.promises = {};
this.socket = socket;
this.socket.on('screenshot', function(data){
var screenshotId = data.id;
this.promises[''+screenshotId].resolve(data.data);
}.bind(this));
this.socket.on('screenshot-error', function(data){
var screenshotId = data.id;
this.promises[''+screenshotId].reject(data.error);
}.bind(this));
};
Browser.prototype.screenshot = function(options){
var deferred = Promise.pending();
options.id = requestId++;
this.socket.emit('take-screenshot', options);
this.promises[''+options.id] = deferred;
return deferred.promise;
};
var _isStarted;
var connection;
var createBrowser = function(options){
_isStarted = new Promise(function(resolve, reject){
io.on('connection', function(socket){
if (!connection) {
resolve( new Browser(socket) );
connection = socket;
}
});
io.on('error', function(error){
reject(error);
});
});
process.env.NWS_PORT = options.port || 3000;
server.listen(process.env.NWS_PORT);
spawn(nodewebkit, [
'.'
],{
cwd: app,
env: process.env
});
return _isStarted;
};
module.exports = {
getBrowser : function(options){
return _isStarted || createBrowser(options);
},
close : function(){
_isStarted = undefined;
if ( connection ){
connection.emit('close');
}
server.close();
}
};