poltergeist.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. Poltergeist = (function () {
  2. /**
  3. * The MAIN class of the project
  4. * @param port
  5. * @param width
  6. * @param height
  7. * @param jsErrors
  8. * @constructor
  9. */
  10. function Poltergeist(port, width, height, jsErrors) {
  11. var self;
  12. this.browser = new Poltergeist.Browser(this, width, height, jsErrors);
  13. this.commandServer = new Poltergeist.Server(this, port);
  14. this.commandServer.start();
  15. self = this;
  16. phantom.onError = function (message, stack) {
  17. return self.onError(message, stack);
  18. };
  19. this.running = false;
  20. }
  21. /**
  22. * Tries to execute a command send by a client and returns the command response
  23. * or error if something happened
  24. * @param command
  25. * @param serverResponse
  26. * @return {boolean}
  27. */
  28. Poltergeist.prototype.serverRunCommand = function (command, serverResponse) {
  29. var error;
  30. this.running = true;
  31. try {
  32. return this.browser.serverRunCommand(command, serverResponse);
  33. } catch (_error) {
  34. error = _error;
  35. if (error instanceof Poltergeist.Error) {
  36. return this.serverSendError(error, serverResponse);
  37. }
  38. return this.serverSendError(new Poltergeist.BrowserError(error.toString(), error.stack), serverResponse);
  39. }
  40. };
  41. /**
  42. * Sends error back to the client
  43. * @param error
  44. * @param serverResponse
  45. * @return {boolean}
  46. */
  47. Poltergeist.prototype.serverSendError = function (error, serverResponse) {
  48. var errorObject;
  49. errorObject = {
  50. error: {
  51. name: error.name || 'Generic',
  52. args: error.args && error.args() || [error.toString()]
  53. }
  54. };
  55. return this.commandServer.sendError(serverResponse, 500, errorObject);
  56. };
  57. /**
  58. * Send the response back to the client
  59. * @param response Data to send to the client
  60. * @param serverResponse Phantomjs response object associated to the client request
  61. * @return {boolean}
  62. */
  63. Poltergeist.prototype.serverSendResponse = function (response, serverResponse) {
  64. return this.commandServer.send(serverResponse, {response: response});
  65. };
  66. return Poltergeist;
  67. })();
  68. window.Poltergeist = Poltergeist;