render.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. (function() {
  2. 'use strict';
  3. var page = require('webpage').create();
  4. var args = require('system').args;
  5. var params = {};
  6. var regexp = /^([^=]+)=([^$]+)/;
  7. args.forEach(function(arg) {
  8. var parts = arg.match(regexp);
  9. if (!parts) { return; }
  10. params[parts[1]] = parts[2];
  11. });
  12. var usage = "url=<url> png=<filename> width=<width> height=<height> renderKey=<key>";
  13. if (!params.url || !params.png || !params.renderKey || !params.domain) {
  14. console.log(usage);
  15. phantom.exit();
  16. }
  17. phantom.addCookie({
  18. 'name': 'renderKey',
  19. 'value': params.renderKey,
  20. 'domain': params.domain,
  21. });
  22. page.viewportSize = {
  23. width: params.width || '800',
  24. height: params.height || '400'
  25. };
  26. var timeoutMs = (parseInt(params.timeout) || 10) * 1000;
  27. var waitBetweenReadyCheckMs = 50;
  28. var totalWaitMs = 0;
  29. page.open(params.url, function (status) {
  30. console.log('Loading a web page: ' + params.url + ' status: ' + status, timeoutMs);
  31. page.onError = function(msg, trace) {
  32. var msgStack = ['ERROR: ' + msg];
  33. if (trace && trace.length) {
  34. msgStack.push('TRACE:');
  35. trace.forEach(function(t) {
  36. msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
  37. });
  38. }
  39. console.error(msgStack.join('\n'));
  40. };
  41. function checkIsReady() {
  42. var panelsRendered = page.evaluate(function() {
  43. if (!window.angular) { return false; }
  44. var body = window.angular.element(document.body);
  45. if (!body.injector) { return false; }
  46. if (!body.injector()) { return false; }
  47. var rootScope = body.injector().get('$rootScope');
  48. if (!rootScope) {return false;}
  49. var panels = angular.element('plugin-component').length;
  50. return rootScope.panelsRendered >= panels;
  51. });
  52. if (panelsRendered || totalWaitMs > timeoutMs) {
  53. var bb = page.evaluate(function () {
  54. return document.getElementsByClassName("main-view")[0].getBoundingClientRect();
  55. });
  56. page.clipRect = {
  57. top: bb.top,
  58. left: bb.left,
  59. width: bb.width,
  60. height: bb.height
  61. };
  62. page.render(params.png);
  63. phantom.exit();
  64. } else {
  65. totalWaitMs += waitBetweenReadyCheckMs;
  66. setTimeout(checkIsReady, waitBetweenReadyCheckMs);
  67. }
  68. }
  69. setTimeout(checkIsReady, waitBetweenReadyCheckMs);
  70. });
  71. })();