webdriver-chromium.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global require, exports, process, setTimeout, clearTimeout, Buffer */
  24. const chrome = require("selenium-webdriver/chrome");
  25. const { Builder } = require("selenium-webdriver");
  26. exports.initialize = async () => { };
  27. exports.getPageData = async options => {
  28. let driver;
  29. try {
  30. const builder = new Builder();
  31. builder.setChromeOptions(getBrowserOptions(options));
  32. driver = builder.forBrowser("chrome").build();
  33. return await getPageData(driver, options);
  34. } finally {
  35. if (driver) {
  36. driver.quit();
  37. }
  38. }
  39. };
  40. exports.closeBrowser = () => { };
  41. function getBrowserOptions(options) {
  42. const chromeOptions = new chrome.Options();
  43. const optionHeadless = (options.browserHeadless === undefined || options.browserHeadless) && !options.browserDebug;
  44. if (optionHeadless) {
  45. chromeOptions.headless();
  46. }
  47. if (options.browserExecutablePath) {
  48. chromeOptions.setChromeBinaryPath(options.browserExecutablePath);
  49. }
  50. if (options.webDriverExecutablePath) {
  51. process.env["PATH"] += ";" + options.webDriverExecutablePath.replace(/chromedriver(\.exe)?$/, "");
  52. }
  53. if (options.browserArgs) {
  54. const args = JSON.parse(options.browserArgs);
  55. args.forEach(argument => chromeOptions.addArguments(argument));
  56. }
  57. if (options.browserDisableWebSecurity === undefined || options.browserDisableWebSecurity) {
  58. chromeOptions.addArguments("--disable-web-security");
  59. }
  60. chromeOptions.addArguments("--no-pings");
  61. if (!optionHeadless) {
  62. if (options.browserDebug) {
  63. chromeOptions.addArguments("--auto-open-devtools-for-tabs");
  64. }
  65. const extensions = [];
  66. if (options.browserBypassCSP === undefined || options.browserBypassCSP) {
  67. extensions.push(encode(require.resolve("./extensions/signed/bypass_csp-0.0.3-an+fx.xpi")));
  68. }
  69. if (options.browserWaitUntil === undefined || options.browserWaitUntil == "networkidle0" || options.browserWaitUntil == "networkidle2") {
  70. extensions.push(encode(require.resolve("./extensions/signed/network_idle-0.0.2-an+fx.xpi")));
  71. }
  72. chromeOptions.addExtensions(extensions);
  73. }
  74. if (options.userAgent) {
  75. chromeOptions.addArguments("--user-agent=" + JSON.stringify(options.userAgent));
  76. }
  77. if (options.browserMobileEmulation) {
  78. chromeOptions.setMobileEmulation({
  79. deviceName: options.browserMobileEmulation
  80. });
  81. }
  82. return chromeOptions;
  83. }
  84. async function getPageData(driver, options) {
  85. const optionHeadless = (options.browserHeadless === undefined || options.browserHeadless) && !options.browserDebug;
  86. driver.manage().setTimeouts({ script: options.browserLoadMaxTime, pageLoad: options.browserLoadMaxTime, implicit: options.browserLoadMaxTime });
  87. if (options.browserWidth && options.browserHeight) {
  88. const window = driver.manage().window();
  89. if (window.setRect) {
  90. window.setRect(options.browserHeight, options.browserWidth);
  91. } else if (window.setSize) {
  92. window.setSize(options.browserWidth, options.browserHeight);
  93. }
  94. }
  95. const scripts = await require("./common/scripts.js").get(options);
  96. if (options.browserDebug) {
  97. // await driver.sleep(3000);
  98. }
  99. await driver.get(options.url);
  100. if (options.browserCookies) {
  101. await Promise.all(options.browserCookies.map(cookie => {
  102. if (cookie.expires) {
  103. cookie.expiry = cookie.expires;
  104. delete cookie.expires;
  105. }
  106. return driver.manage().addCookie(cookie);
  107. }));
  108. await driver.get(options.url);
  109. }
  110. await driver.executeScript(scripts);
  111. if (options.browserWaitUntil != "domcontentloaded") {
  112. let scriptPromise;
  113. if (!optionHeadless && (options.browserWaitUntil === undefined || options.browserWaitUntil == "networkidle0")) {
  114. scriptPromise = driver.executeAsyncScript("addEventListener(\"single-file-network-idle-0\", () => arguments[0](), true)");
  115. } else if (!optionHeadless && options.browserWaitUntil == "networkidle2") {
  116. scriptPromise = driver.executeAsyncScript("addEventListener(\"single-file-network-idle-2\", () => arguments[0](), true)");
  117. } else if (optionHeadless || options.browserWaitUntil == "load") {
  118. scriptPromise = driver.executeAsyncScript("if (document.readyState == \"loading\" || document.readyState == \"interactive\") { addEventListener(\"load\", () => arguments[0]()) } else { arguments[0](); }");
  119. }
  120. let cancelTimeout;
  121. const timeoutPromise = new Promise(resolve => {
  122. const timeoutId = setTimeout(resolve, Math.max(0, options.browserLoadMaxTime - 5000));
  123. cancelTimeout = () => {
  124. clearTimeout(timeoutId);
  125. resolve();
  126. };
  127. });
  128. await Promise.race([scriptPromise, timeoutPromise]);
  129. cancelTimeout();
  130. }
  131. if (options.browserWaitDelay) {
  132. await driver.sleep(options.browserWaitDelay);
  133. }
  134. const result = await driver.executeAsyncScript(getPageDataScript(), options);
  135. if (result.error) {
  136. throw result.error;
  137. } else {
  138. return result.pageData;
  139. }
  140. }
  141. function encode(file) {
  142. return new Buffer.from(require("fs").readFileSync(file)).toString("base64");
  143. }
  144. function getPageDataScript() {
  145. return `
  146. const [options, callback] = arguments;
  147. getPageData()
  148. .then(pageData => callback({ pageData }))
  149. .catch(error => callback({ error: error && error.toString() }));
  150. async function getPageData() {
  151. const pageData = await singlefile.getPageData(options);
  152. if (options.includeInfobar) {
  153. await infobar.includeScript(pageData);
  154. }
  155. return pageData;
  156. }
  157. `;
  158. }