Best JavaScript code snippet using puppeteer
renderPaymentMethod.js
Source: renderPaymentMethod.js 
1"use strict";2var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));3function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }4function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }5function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }6function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }7function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }8function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }9var store = require('../../../../store');10var helpers = require('./helpers');11var _require = require('./qrCodeMethods'),12    qrCodeMethods = _require.qrCodeMethods;13function getFallback(paymentMethod) {14  var fallback = {15    giftcard: "\n        <input type=\"hidden\" class=\"brand\" name=\"brand\" value=\"".concat(paymentMethod.brand, "\"/>\n        <input type=\"hidden\" class=\"type\" name=\"type\" value=\"").concat(paymentMethod.type, "\"/>")16  };17  if (fallback[paymentMethod.type]) {18    store.componentsObj[paymentMethod.type] = {};19  }20  return fallback[paymentMethod.type];21}22function getPersonalDetails() {23  var _document$querySelect, _document$querySelect2, _document$querySelect3, _document$querySelect4, _document$querySelect5, _document$querySelect6, _document$querySelect7, _document$querySelect8, _document$querySelect9, _document$querySelect10, _document$querySelect11, _document$querySelect12, _document$querySelect13, _document$querySelect14, _document$querySelect15, _document$querySelect16;24  return {25    firstName: (_document$querySelect = document.querySelector('#shippingFirstNamedefault')) === null || _document$querySelect === void 0 ? void 0 : _document$querySelect.value,26    lastName: (_document$querySelect2 = document.querySelector('#shippingLastNamedefault')) === null || _document$querySelect2 === void 0 ? void 0 : _document$querySelect2.value,27    telephoneNumber: (_document$querySelect3 = document.querySelector('#shippingPhoneNumberdefault')) === null || _document$querySelect3 === void 0 ? void 0 : _document$querySelect3.value,28    shopperEmail: (_document$querySelect4 = document.querySelector('.customer-summary-email')) === null || _document$querySelect4 === void 0 ? void 0 : _document$querySelect4.textContent,29    billingAddress: {30      city: (_document$querySelect5 = document.querySelector('#billingAddressCity')) === null || _document$querySelect5 === void 0 ? void 0 : _document$querySelect5.value,31      postalCode: (_document$querySelect6 = document.querySelector('#billingZipCode')) === null || _document$querySelect6 === void 0 ? void 0 : _document$querySelect6.value,32      country: (_document$querySelect7 = document.querySelector('#billingCountry')) === null || _document$querySelect7 === void 0 ? void 0 : _document$querySelect7.value,33      stateOrProvince: (_document$querySelect8 = document.querySelector('#billingState')) === null || _document$querySelect8 === void 0 ? void 0 : _document$querySelect8.value,34      street: (_document$querySelect9 = document.querySelector('#billingAddressOne')) === null || _document$querySelect9 === void 0 ? void 0 : _document$querySelect9.value,35      houseNumberOrName: (_document$querySelect10 = document.querySelector('#billingAddressTwo')) === null || _document$querySelect10 === void 0 ? void 0 : _document$querySelect10.value36    },37    deliveryAddress: {38      city: (_document$querySelect11 = document.querySelector('#shippingAddressCitydefault')) === null || _document$querySelect11 === void 0 ? void 0 : _document$querySelect11.value,39      postalCode: (_document$querySelect12 = document.querySelector('#shippingZipCodedefault')) === null || _document$querySelect12 === void 0 ? void 0 : _document$querySelect12.value,40      country: (_document$querySelect13 = document.querySelector('#shippingCountrydefault')) === null || _document$querySelect13 === void 0 ? void 0 : _document$querySelect13.value,41      stateOrProvince: (_document$querySelect14 = document.querySelector('#shippingStatedefault')) === null || _document$querySelect14 === void 0 ? void 0 : _document$querySelect14.value,42      street: (_document$querySelect15 = document.querySelector('#shippingAddressOnedefault')) === null || _document$querySelect15 === void 0 ? void 0 : _document$querySelect15.value,43      houseNumberOrName: (_document$querySelect16 = document.querySelector('#shippingAddressTwodefault')) === null || _document$querySelect16 === void 0 ? void 0 : _document$querySelect16.value44    }45  };46}47function setNode(paymentMethodID) {48  var createNode = function createNode() {49    if (!store.componentsObj[paymentMethodID]) {50      store.componentsObj[paymentMethodID] = {};51    }52    try {53      var _store$checkout;54      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {55        args[_key] = arguments[_key];56      }57      // ALl nodes created for the checkout component are enriched with shopper personal details58      var node = (_store$checkout = store.checkout).create.apply(_store$checkout, args.concat([{59        data: _objectSpread(_objectSpread({}, getPersonalDetails()), {}, {60          personalDetails: getPersonalDetails()61        })62      }]));63      store.componentsObj[paymentMethodID].node = node;64    } catch (e) {65      /* No component for payment method */66    }67  };68  return createNode;69}70function getPaymentMethodID(isStored, paymentMethod) {71  if (isStored) {72    return "storedCard".concat(paymentMethod.id);73  }74  if (paymentMethod.brand) {75    // gift cards all share the same type. Brand is used to differentiate between them76    return "".concat(paymentMethod.type, "_").concat(paymentMethod.brand);77  }78  return paymentMethod.type;79}80function getImage(isStored, paymentMethod) {81  return isStored ? paymentMethod.brand : paymentMethod.type;82}83function getLabel(isStored, paymentMethod) {84  var label = isStored ? " ".concat(store.MASKED_CC_PREFIX).concat(paymentMethod.lastFour) : '';85  return "".concat(paymentMethod.name).concat(label);86}87function handleFallbackPayment(_ref) {88  var paymentMethod = _ref.paymentMethod,89      container = _ref.container,90      paymentMethodID = _ref.paymentMethodID;91  var fallback = getFallback(paymentMethod);92  var createTemplate = function createTemplate() {93    var template = document.createElement('template');94    template.innerHTML = fallback;95    container.append(template.content);96  };97  return fallback ? createTemplate() : setNode(paymentMethod.type)(paymentMethodID);98}99function handlePayment(options) {100  return options.isStored ? setNode(options.paymentMethodID)('card', options.paymentMethod) : handleFallbackPayment(options);101}102function getListContents(_ref2) {103  var imagePath = _ref2.imagePath,104      isStored = _ref2.isStored,105      paymentMethod = _ref2.paymentMethod,106      description = _ref2.description;107  var paymentMethodID = getPaymentMethodID(isStored, paymentMethod);108  var label = getLabel(isStored, paymentMethod);109  var liContents = "\n    <input name=\"brandCode\" type=\"radio\" value=\"".concat(paymentMethodID, "\" id=\"rb_").concat(paymentMethodID, "\">\n    <img class=\"paymentMethod_img\" src=\"").concat(imagePath, "\" ></img>\n    <label id=\"lb_").concat(paymentMethodID, "\" for=\"rb_").concat(paymentMethodID, "\">").concat(label, "</label>\n  ");110  return description ? "".concat(liContents, "<p>").concat(description, "</p>") : liContents;111}112function getImagePath(_ref3) {113  var isStored = _ref3.isStored,114      paymentMethod = _ref3.paymentMethod,115      path = _ref3.path,116      isSchemeNotStored = _ref3.isSchemeNotStored;117  var paymentMethodImage = "".concat(path).concat(getImage(isStored, paymentMethod), ".png");118  var cardImage = "".concat(path, "card.png");119  return isSchemeNotStored ? cardImage : paymentMethodImage;120}121function hasNoChildNodes(_ref4) {122  var paymentMethodID = _ref4.paymentMethodID,123      container = _ref4.container;124  return store.componentsObj[paymentMethodID] && !container.childNodes[0];125}126function setValid(_ref5) {127  var paymentMethodID = _ref5.paymentMethodID,128      container = _ref5.container;129  if (hasNoChildNodes({130    paymentMethodID: paymentMethodID,131    container: container132  }) && ['bcmc', 'scheme'].indexOf(paymentMethodID) === -1) {133    store.componentsObj[paymentMethodID].isValid = true;134  }135}136function configureContainer(_ref6) {137  var paymentMethodID = _ref6.paymentMethodID,138      container = _ref6.container;139  container.classList.add('additionalFields');140  container.setAttribute('id', "component_".concat(paymentMethodID));141  container.setAttribute('style', 'display:none');142}143function handleInput(_ref7) {144  var paymentMethodID = _ref7.paymentMethodID;145  var input = document.querySelector("#rb_".concat(paymentMethodID));146  input.onchange = /*#__PURE__*/function () {147    var _ref8 = _asyncToGenerator( /*#__PURE__*/_regenerator["default"].mark(function _callee(event) {148      var _store$componentsObj$, compName, qrComponent, node;149      return _regenerator["default"].wrap(function _callee$(_context) {150        while (1) {151          switch (_context.prev = _context.next) {152            case 0:153              if (!(document.querySelector('.adyen-checkout__qr-loader') && qrCodeMethods.indexOf(store.selectedMethod) > -1)) {154                _context.next = 10;155                break;156              }157              compName = store.selectedMethod;158              qrComponent = store.componentsObj[compName];159              _context.next = 5;160              return Promise.resolve(qrComponent.node.unmount("component_".concat(compName)));161            case 5:162              delete store.componentsObj[compName];163              setNode(compName)(compName);164              node = (_store$componentsObj$ = store.componentsObj[compName]) === null || _store$componentsObj$ === void 0 ? void 0 : _store$componentsObj$.node;165              if (node) {166                node.mount(document.querySelector("#component_".concat(compName)));167              }168              helpers.paymentFromComponent({169                cancelTransaction: true,170                merchantReference: document.querySelector('#merchantReference').value171              });172            case 10:173              helpers.displaySelectedMethod(event.target.value);174            case 11:175            case "end":176              return _context.stop();177          }178        }179      }, _callee);180    }));181    return function (_x) {182      return _ref8.apply(this, arguments);183    };184  }();185}186module.exports.renderPaymentMethod = function renderPaymentMethod(paymentMethod, isStored, path) {187  var _store$componentsObj$2;188  var description = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;189  var paymentMethodsUI = document.querySelector('#paymentMethodsList');190  var li = document.createElement('li');191  var paymentMethodID = getPaymentMethodID(isStored, paymentMethod);192  var isSchemeNotStored = paymentMethod.type === 'scheme' && !isStored;193  var container = document.createElement('div');194  var options = {195    container: container,196    paymentMethod: paymentMethod,197    isStored: isStored,198    path: path,199    description: description,200    paymentMethodID: paymentMethodID,201    isSchemeNotStored: isSchemeNotStored202  };203  var imagePath = getImagePath(options);204  var liContents = getListContents(_objectSpread(_objectSpread({}, options), {}, {205    imagePath: imagePath206  }));207  li.innerHTML = liContents;208  li.classList.add('paymentMethod');209  handlePayment(options);210  configureContainer(options);211  li.append(container);212  paymentMethodsUI.append(li);213  var node = (_store$componentsObj$2 = store.componentsObj[paymentMethodID]) === null || _store$componentsObj$2 === void 0 ? void 0 : _store$componentsObj$2.node;214  if (node) {215    node.mount(container);216  }217  if (paymentMethodID === 'giropay') {218    container.innerHTML = '';219  }220  handleInput(options);221  setValid(options);...gsSuspendedTab.js
Source: gsSuspendedTab.js 
1/*global tgs, gsFavicon, gsStorage, gsSession, gsUtils, gsIndexedDb */2// eslint-disable-next-line no-unused-vars3var gsSuspendedTab = (function() {4  'use strict';5  async function initTab(tab, tabView, { quickInit }) {6    if (!tabView) {7      gsUtils.warning(8        tab.id,9        'Could not get internalTabView for suspended tab'10      );11    }12    const suspendedUrl = tab.url;13    // Set sessionId for subsequent checks14    tabView.document.sessionId = gsSession.getSessionId();15    // Set title16    let title = gsUtils.getSuspendedTitle(suspendedUrl);17    if (title.indexOf('<') >= 0) {18      // Encode any raw html tags that might be used in the title19      title = gsUtils.htmlEncode(title);20    }21    setTitle(tabView.document, title);22    // Set faviconMeta23    const faviconMeta = await gsFavicon.getFaviconMetaData(tab);24    setFaviconMeta(tabView.document, faviconMeta);25    if (quickInit) {26      return;27    }28    gsUtils.localiseHtml(tabView.document);29    const options = gsStorage.getSettings();30    const originalUrl = gsUtils.getOriginalUrl(suspendedUrl);31    // Add event listeners32    setUnloadTabHandler(tabView.window, tab);33    setUnsuspendTabHandlers(tabView.document, tab);34    // Set imagePreview35    const previewMode = options[gsStorage.SCREEN_CAPTURE];36    const previewUri = await getPreviewUri(suspendedUrl);37    await toggleImagePreviewVisibility(38      tabView.document,39      tab,40      previewMode,41      previewUri42    );43    // Set theme44    const theme = options[gsStorage.THEME];45    const isLowContrastFavicon = faviconMeta.isDark;46    setTheme(tabView.document, theme, isLowContrastFavicon);47    // Set command48    const suspensionToggleHotkey = await tgs.getSuspensionToggleHotkey();49    setCommand(tabView.document, suspensionToggleHotkey);50    // Set url51    setUrl(tabView.document, originalUrl);52    // Set reason53    const suspendReasonInt = tgs.getTabStatePropForTabId(54      tab.id,55      tgs.STATE_SUSPEND_REASON56    );57    let suspendReason = null;58    if (suspendReasonInt === 3) {59      suspendReason = chrome.i18n.getMessage('js_suspended_low_memory');60    }61    setReason(tabView.document, suspendReason);62    // Show the view63    showContents(tabView.document);64    // Set scrollPosition (must come after showing page contents)65    const scrollPosition = gsUtils.getSuspendedScrollPosition(suspendedUrl);66    setScrollPosition(tabView.document, scrollPosition, previewMode);67    tgs.setTabStatePropForTabId(tab.id, tgs.STATE_SCROLL_POS, scrollPosition);68    // const whitelisted = gsUtils.checkWhiteList(originalUrl);69  }70  function showNoConnectivityMessage(tabView) {71    if (!tabView.document.getElementById('disconnectedNotice')) {72      loadToastTemplate(tabView.document);73    }74    tabView.document.getElementById('disconnectedNotice').style.display =75      'none';76    setTimeout(function() {77      tabView.document.getElementById('disconnectedNotice').style.display =78        'block';79    }, 50);80  }81  function updateCommand(tabView, suspensionToggleHotkey) {82    setCommand(tabView.document, suspensionToggleHotkey);83  }84  function updateTheme(tabView, tab, theme, isLowContrastFavicon) {85    setTheme(tabView.document, theme, isLowContrastFavicon);86  }87  async function updatePreviewMode(tabView, tab, previewMode) {88    const previewUri = await getPreviewUri(tab.url);89    await toggleImagePreviewVisibility(90      tabView.document,91      tab,92      previewMode,93      previewUri94    );95    const scrollPosition = gsUtils.getSuspendedScrollPosition(tab.url);96    setScrollPosition(tabView.document, scrollPosition, previewMode);97  }98  function showContents(_document) {99    _document.querySelector('body').classList.remove('hide-initially');100  }101  function setScrollPosition(_document, scrollPosition, previewMode) {102    const scrollPosAsInt = (scrollPosition && parseInt(scrollPosition)) || 0;103    const scrollImagePreview = previewMode === '2';104    if (scrollImagePreview && scrollPosAsInt > 15) {105      const offsetScrollPosition = scrollPosAsInt + 151;106      _document.body.scrollTop = offsetScrollPosition;107      _document.documentElement.scrollTop = offsetScrollPosition;108    } else {109      _document.body.scrollTop = 0;110      _document.documentElement.scrollTop = 0;111    }112  }113  function setTitle(_document, title) {114    _document.title = title;115    _document.getElementById('gsTitle').innerHTML = title;116    _document.getElementById('gsTopBarTitle').innerHTML = title;117    // Prevent unsuspend by parent container118    // Using mousedown event otherwise click can still be triggered if119    // mouse is released outside of this element120    _document.getElementById('gsTopBarTitle').onmousedown = function(e) {121      e.stopPropagation();122    };123  }124  function setUrl(_document, url) {125    _document.getElementById('gsTopBarUrl').innerHTML = cleanUrl(url);126    _document.getElementById('gsTopBarUrl').setAttribute('href', url);127    _document.getElementById('gsTopBarUrl').onmousedown = function(e) {128      e.stopPropagation();129    };130  }131  function setFaviconMeta(_document, faviconMeta) {132    _document133      .getElementById('gsTopBarImg')134      .setAttribute('src', faviconMeta.normalisedDataUrl);135    _document136      .getElementById('gsFavicon')137      .setAttribute('href', faviconMeta.transparentDataUrl);138  }139  function setTheme(_document, theme, isLowContrastFavicon) {140    if (theme === 'dark') {141      _document.querySelector('body').classList.add('dark');142    } else {143      _document.querySelector('body').classList.remove('dark');144    }145    if (theme === 'dark' && isLowContrastFavicon) {146      _document147        .getElementById('faviconWrap')148        .classList.add('faviconWrapLowContrast');149    } else {150      _document151        .getElementById('faviconWrap')152        .classList.remove('faviconWrapLowContrast');153    }154  }155  function setReason(_document, reason) {156    let reasonMsgEl = _document.getElementById('reasonMsg');157    if (!reasonMsgEl) {158      reasonMsgEl = _document.createElement('div');159      reasonMsgEl.setAttribute('id', 'reasonMsg');160      reasonMsgEl.classList.add('reasonMsg');161      const containerEl = _document.getElementById('suspendedMsg-instr');162      containerEl.insertBefore(reasonMsgEl, containerEl.firstChild);163    }164    reasonMsgEl.innerHTML = reason;165  }166  async function getPreviewUri(suspendedUrl) {167    const originalUrl = gsUtils.getOriginalUrl(suspendedUrl);168    const preview = await gsIndexedDb.fetchPreviewImage(originalUrl);169    let previewUri = null;170    if (171      preview &&172      preview.img &&173      preview.img !== null &&174      preview.img !== 'data:,' &&175      preview.img.length > 10000176    ) {177      previewUri = preview.img;178    }179    return previewUri;180  }181  function buildImagePreview(_document, tab, previewUri) {182    return new Promise(resolve => {183      const previewEl = _document.createElement('div');184      const bodyEl = _document.getElementsByTagName('body')[0];185      previewEl.setAttribute('id', 'gsPreviewContainer');186      previewEl.classList.add('gsPreviewContainer');187      previewEl.innerHTML = _document.getElementById(188        'previewTemplate'189      ).innerHTML;190      const unsuspendTabHandler = buildUnsuspendTabHandler(_document, tab);191      previewEl.onclick = unsuspendTabHandler;192      gsUtils.localiseHtml(previewEl);193      bodyEl.appendChild(previewEl);194      const previewImgEl = _document.getElementById('gsPreviewImg');195      const onLoadedHandler = function() {196        previewImgEl.removeEventListener('load', onLoadedHandler);197        previewImgEl.removeEventListener('error', onLoadedHandler);198        resolve();199      };200      previewImgEl.setAttribute('src', previewUri);201      previewImgEl.addEventListener('load', onLoadedHandler);202      previewImgEl.addEventListener('error', onLoadedHandler);203    });204  }205  function addWatermarkHandler(_document) {206    _document.querySelector('.watermark').onclick = () => {207      chrome.tabs.create({ url: chrome.extension.getURL('about.html') });208    };209  }210  async function toggleImagePreviewVisibility(211    _document,212    tab,213    previewMode,214    previewUri215  ) {216    const builtImagePreview =217      _document.getElementById('gsPreviewContainer') !== null;218    if (219      !builtImagePreview &&220      previewUri &&221      previewMode &&222      previewMode !== '0'223    ) {224      await buildImagePreview(_document, tab, previewUri);225    } else {226      addWatermarkHandler(_document);227    }228    if (!_document.getElementById('gsPreviewContainer')) {229      return;230    }231    const overflow = previewMode === '2' ? 'auto' : 'hidden';232    _document.body.style['overflow'] = overflow;233    if (previewMode === '0' || !previewUri) {234      _document.getElementById('gsPreviewContainer').style.display = 'none';235      _document.getElementById('suspendedMsg').style.display = 'flex';236      _document.body.classList.remove('img-preview-mode');237    } else {238      _document.getElementById('gsPreviewContainer').style.display = 'block';239      _document.getElementById('suspendedMsg').style.display = 'none';240      _document.body.classList.add('img-preview-mode');241    }242  }243  function setCommand(_document, command) {244    const hotkeyEl = _document.getElementById('hotkeyWrapper');245    if (command) {246      hotkeyEl.innerHTML =247        '<span class="hotkeyCommand">(' + command + ')</span>';248    } else {249      const reloadString = chrome.i18n.getMessage(250        'js_suspended_hotkey_to_reload'251      );252      hotkeyEl.innerHTML = `<a id="setKeyboardShortcut" href="#">${reloadString}</a>`;253    }254  }255  function setUnloadTabHandler(_window, tab) {256    // beforeunload event will get fired if: the tab is refreshed, the url is changed,257    // the tab is closed, or the tab is frozen by chrome ??258    // when this happens the STATE_UNLOADED_URL gets set with the suspended tab url259    // if the tab is refreshed, then on reload the url will match and the tab will unsuspend260    // if the url is changed then on reload the url will not match261    // if the tab is closed, the reload will never occur262    _window.addEventListener('beforeunload', function(e) {263      gsUtils.log(tab.id, 'BeforeUnload triggered: ' + tab.url);264      if (tgs.isCurrentFocusedTab(tab)) {265        tgs.setTabStatePropForTabId(tab.id, tgs.STATE_UNLOADED_URL, tab.url);266      } else {267        gsUtils.log(268          tab.id,269          'Ignoring beforeUnload as tab is not currently focused.'270        );271      }272    });273  }274  function setUnsuspendTabHandlers(_document, tab) {275    const unsuspendTabHandler = buildUnsuspendTabHandler(_document, tab);276    _document.getElementById('gsTopBarUrl').onclick = unsuspendTabHandler;277    _document.getElementById('gsTopBar').onmousedown = unsuspendTabHandler;278    _document.getElementById('suspendedMsg').onclick = unsuspendTabHandler;279  }280  function buildUnsuspendTabHandler(_document, tab) {281    return function(e) {282      e.preventDefault();283      e.stopPropagation();284      if (e.target.id === 'setKeyboardShortcut') {285        chrome.tabs.create({ url: 'chrome://extensions/shortcuts' });286      } else if (e.which === 1) {287        showUnsuspendAnimation(_document);288        tgs.unsuspendTab(tab);289      }290    };291  }292  function showUnsuspendAnimation(_document) {293    if (_document.body.classList.contains('img-preview-mode')) {294      _document.getElementById('refreshSpinner').classList.add('spinner');295    } else {296      _document.body.classList.add('waking');297      _document.getElementById('snoozyImg').src = chrome.extension.getURL(298        'img/snoozy_tab_awake.svg'299      );300      _document.getElementById('snoozySpinner').classList.add('spinner');301    }302  }303  function loadToastTemplate(_document) {304    const toastEl = _document.createElement('div');305    toastEl.setAttribute('id', 'disconnectedNotice');306    toastEl.classList.add('toast-wrapper');307    toastEl.innerHTML = _document.getElementById('toastTemplate').innerHTML;308    gsUtils.localiseHtml(toastEl);309    _document.getElementsByTagName('body')[0].appendChild(toastEl);310  }311  function cleanUrl(urlStr) {312    // remove scheme313    if (urlStr.indexOf('//') > 0) {314      urlStr = urlStr.substring(urlStr.indexOf('//') + 2);315    }316    // remove query string317    let match = urlStr.match(/\/?[?#]+/);318    if (match) {319      urlStr = urlStr.substring(0, match.index);320    }321    // remove trailing slash322    match = urlStr.match(/\/$/);323    if (match) {324      urlStr = urlStr.substring(0, match.index);325    }326    return urlStr;327  }328  return {329    initTab,330    showNoConnectivityMessage,331    updateCommand,332    updateTheme,333    updatePreviewMode,334  };...calendar-event-dialog.js
Source: calendar-event-dialog.js 
1/* ***** BEGIN LICENSE BLOCK *****2 * Version: GPL 3.03 *4 * The contents of this file are subject to the General Public License5 * 3.0 (the "License"); you may not use this file except in compliance with6 * the License. You may obtain a copy of the License at7 * http://www.gnu.org/licenses/gpl.html8 *9 * Software distributed under the License is distributed on an "AS IS" basis,10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License11 * for the specific language governing rights and limitations under the12 * License.13 *14 * -- Exchange 2007/2010 Calendar and Tasks Provider.15 * -- For Thunderbird with the Lightning add-on.16 *17 * Author: Michel Verbraak (info@1st-setup.nl)18 * Website: http://www.1st-setup.nl/wordpress/?page_id=13319 * email: exchangecalendar@extensions.1st-setup.nl20 *21 *22 * This code uses parts of the Microsoft Exchange Calendar Provider code on which the23 * "Exchange Data Provider for Lightning" was based.24 * The Initial Developer of the Microsoft Exchange Calendar Provider Code is25 *   Andrea Bittau <a.bittau@cs.ucl.ac.uk>, University College London26 * Portions created by the Initial Developer are Copyright (C) 200927 * the Initial Developer. All Rights Reserved.28 *29 * ***** BEGIN LICENSE BLOCK *****/30var Cu = Components.utils;31var Ci = Components.interfaces;32var Cc = Components.classes;33Cu.import("resource://calendar/modules/calUtils.jsm");34Cu.import("resource://gre/modules/Services.jsm");35function exchEventDialog(aDocument, aWindow)36{37	this._document = aDocument;38	this._window = aWindow;39	this.globalFunctions = Cc["@1st-setup.nl/global/functions;1"]40				.getService(Ci.mivFunctions);41}42exchEventDialog.prototype = {43	_initialized: false,44	_oldCallback: null,45	onAcceptCallback: function _onAcceptCallback(aItem, aCalendar, aOriginalItem, aIsClosing)46	{47		if ((cal.isEvent(aItem)) && (aCalendar.type == "exchangecalendar")) {48			if (!aItem.className) {49				var newItem = Cc["@1st-setup.nl/exchange/calendarevent;1"]50						.createInstance(Ci.mivExchangeEvent);51				newItem.cloneToCalEvent(aItem);52				aItem = newItem;53			}54		}55		if ((!cal.isEvent(aItem)) && (aCalendar.type == "exchangecalendar")) {56			// Save extra exchange fields to item.57			if (!aItem.className) {58				var newItem = Cc["@1st-setup.nl/exchange/calendartodo;1"]59						.createInstance(Ci.mivExchangeTodo);60				newItem.cloneToCalEvent(aItem);61				aItem = newItem;62			}63			aItem.totalWork = this._document.getElementById("exchWebService-totalWork-count").value;64			aItem.actualWork = this._document.getElementById("exchWebService-actualWork-count").value;65			aItem.mileage = this._document.getElementById("exchWebService-mileage-count").value;66			aItem.billingInformation = this._document.getElementById("exchWebService-billingInformation-count").value;67			aItem.companies = this._document.getElementById("exchWebService-companies-count").value;68		}69try{70		if (this.newItem) {71			aItem.bodyType = "HTML";72			aItem.body = this._document.getElementById("exchWebService-body-editor").content;73		}74		else {75			if (aItem.bodyType == "HTML") {76				aItem.body = this._document.getElementById("exchWebService-body-editor").content;77			}78		}79}catch(err){dump("Error saving content\n");}80		if (this._oldCallback) {81			this._oldCallback(aItem, aCalendar, aOriginalItem, aIsClosing);82		}83	},84	onLoad: function _onLoad()85	{86		//onLoad();87		if (this._window.arguments[0].calendarEvent.calendar.type != "exchangecalendar") {88			if (this._document.getElementById("item-description")) {89				this._document.getElementById("item-description").hidden = false;90			}91			if (this._document.getElementById("exchWebService-body-editor")) {92				this._document.getElementById("exchWebService-body-editor").hidden = true;93			}94			return;95		}96		if (this._initialized) return;97		this._oldCallback = this._window.onAcceptCallback;98		var self = this;99		this._window.onAcceptCallback = function(aItem, aCalendar, aOriginalItem, aIsClosing) { self.onAcceptCallback(aItem, aCalendar, aOriginalItem, aIsClosing); };100		if (this._document.getElementById("todo-entrydate")) {101			this._initialized = true;102			var args = this._window.arguments[0];103			var item = args.calendarEvent;104			this.updateScreen(item, item.calendar);105			//Cc["@mozilla.org/consoleservice;1"]106	                //     .getService(Ci.nsIConsoleService).logStringMessage(item.exchangeXML);107//dump("event.dialog: item.exchangeXML:"+item.exchangeXML+"\n");108			if ((item.bodyType == "HTML") || (item.bodyType === undefined)) {109				if (this._document.getElementById("item-description")) {110					this._document.getElementById("item-description").hidden = true;111				}112				if (this._document.getElementById("exchWebService-body-editor")) {113					this._document.getElementById("exchWebService-body-editor").hidden = false;114					if (item.bodyType !== undefined) {115						this._document.getElementById("exchWebService-body-editor").content = item.body;116					}117					else {118						this.newItem = true;119						if (item.body) {120							if ((item.body.indexOf("<BODY>") > -1) || (item.body.indexOf("<body>") > -1)) {121								this._document.getElementById("exchWebService-body-editor").content = item.body;122							}123							else {124								this._document.getElementById("exchWebService-body-editor").content = this.globalFunctions.fromText2HTML(item.getProperty("DESCRIPTION"));125							}126						}127						else {128							this._document.getElementById("exchWebService-body-editor").content = this.globalFunctions.fromText2HTML(item.getProperty("DESCRIPTION"));129						}130					}131				}132			}133			else {134				if (this._document.getElementById("item-description")) {135					this._document.getElementById("item-description").hidden = false;136				}137				if (this._document.getElementById("exchWebService-body-editor")) {138					this._document.getElementById("exchWebService-body-editor").hidden = true;139				}140			}141		}142	},143	updateScreen: function _updateScreen(aItem, aCalendar)144	{145		var item = aItem;146		if ((!cal.isEvent(item)) && (aCalendar.type == "exchangecalendar")) {147			var ownerLabel = this._document.getElementById("exchWebService-owner-label");148			if (ownerLabel) {149				ownerLabel.value = item.owner;150			}151			try {152				this._document.getElementById("exchWebService-details-row1").removeAttribute("collapsed");153				this._document.getElementById("exchWebService-details-row2").removeAttribute("collapsed");154				this._document.getElementById("exchWebService-details-row3").removeAttribute("collapsed");155			}156			catch (ex) {}157			this._document.getElementById("exchWebService-owner-row").setAttribute("collapsed", "false");158			this._document.getElementById("exchWebService-details-separator").hidden = false;159			if (item.className) {160				this._document.getElementById("exchWebService-totalWork-count").value = item.totalWork;161				this._document.getElementById("exchWebService-actualWork-count").value = item.actualWork;162				this._document.getElementById("exchWebService-mileage-count").value = item.mileage;163				this._document.getElementById("exchWebService-billingInformation-count").value = item.billingInformation;164				this._document.getElementById("exchWebService-companies-count").value = item.companies;165			}166			this._document.getElementById("event-grid-location-row").hidden = true;167			// Clear reminder select list for todo168			this._document.getElementById("reminder-none-separator").hidden = true;169			this._document.getElementById("reminder-0minutes-menuitem").hidden = true;170			this._document.getElementById("reminder-5minutes-menuitem").hidden = true;171			this._document.getElementById("reminder-15minutes-menuitem").hidden = true;172			this._document.getElementById("reminder-30minutes-menuitem").hidden = true;173			this._document.getElementById("reminder-minutes-separator").hidden = true;174			this._document.getElementById("reminder-1hour-menuitem").hidden = true;175			this._document.getElementById("reminder-2hours-menuitem").hidden = true;176			this._document.getElementById("reminder-12hours-menuitem").hidden = true;177			this._document.getElementById("reminder-hours-separator").hidden = true;178			this._document.getElementById("reminder-1day-menuitem").hidden = true;179			this._document.getElementById("reminder-2days-menuitem").hidden = true;180			this._document.getElementById("reminder-1week-menuitem").hidden = true;181			182			this._document.getElementById("timezone-starttime").hidden = true;183			this._document.getElementById("timezone-endtime").hidden = true;184			if (this._document.getElementById("item-repeat")) {185				this._document.getElementById("item-repeat").addEventListener("command", function() { self.updateRepeat(); }, false);186			}187			//this.updateTime();188			this.updateRepeat();189		}190		else {191			try {192				this._document.getElementById("exchWebService-details-row1").setAttribute("collapsed", "true");193				this._document.getElementById("exchWebService-details-row2").setAttribute("collapsed", "true");194				this._document.getElementById("exchWebService-details-row3").setAttribute("collapsed", "true");195			}196			catch (ex) {}197			this._document.getElementById("exchWebService-owner-row").setAttribute("collapsed", "true");198			this._document.getElementById("exchWebService-details-separator").hidden = true;199			this._document.getElementById("event-grid-location-row").hidden = false;200			// Clear reminder select list for todo201			this._document.getElementById("reminder-none-separator").hidden = false;202			this._document.getElementById("reminder-0minutes-menuitem").hidden = false;203			this._document.getElementById("reminder-5minutes-menuitem").hidden = false;204			this._document.getElementById("reminder-15minutes-menuitem").hidden = false;205			this._document.getElementById("reminder-30minutes-menuitem").hidden = false;206			this._document.getElementById("reminder-minutes-separator").hidden = false;207			this._document.getElementById("reminder-1hour-menuitem").hidden = false;208			this._document.getElementById("reminder-2hours-menuitem").hidden = false;209			this._document.getElementById("reminder-12hours-menuitem").hidden = false;210			this._document.getElementById("reminder-hours-separator").hidden = false;211			this._document.getElementById("reminder-1day-menuitem").hidden = false;212			this._document.getElementById("reminder-2days-menuitem").hidden = false;213			this._document.getElementById("reminder-1week-menuitem").hidden = false;214			this._document.getElementById("timezone-starttime").hidden = false;215			this._document.getElementById("timezone-endtime").hidden = false;216		}217	},218	// This will remove the time value from the repeat part and tooltip.219	updateRepeat: function _updateRepeat()220	{221		var repeatDetails = this._document.getElementById("repeat-details").childNodes;222		if (repeatDetails.length == 3) {223			this._document.getElementById("repeat-details").removeChild(repeatDetails[2]);224			var toolTip = repeatDetails[0].getAttribute("tooltiptext");225			var tmpArray = toolTip.split("\n");226			tmpArray.splice(2,1);227			repeatDetails[0].setAttribute("tooltiptext", tmpArray.join("\n"));228			repeatDetails[1].setAttribute("tooltiptext", tmpArray.join("\n"));229		}230	},231	selectedCalendarChanged: function _selectedCalendarChanged(aMenuList)232	{233		updateCalendar();234		this.updateScreen(this._window.calendarItem, getCurrentCalendar());235	},236}237var tmpEventDialog = new exchEventDialog(document, window);...area.js
Source: area.js 
1/*2 * ------------------------------------------3 * å¯åªä½ç¼è¾å¨è¾å
¥åºå°è£
å®ç°æä»¶4 * @version  1.05 * @author   genify(caijf@corp.netease.com)6 * ------------------------------------------7 */8var f = function(){9    var _  = NEJ.P,10        _o = NEJ.O,11        _v = _('nej.v'),12        _e = _('nej.e'),13        _u = _('nej.u'),14        _h = _('nej.h'),15        _p = _('nej.ut'),16        _pro;17    if (!!_p._$$EditorArea) return;18    /**19     * å¯åªä½ç¼è¾å¨è¾å
¥åºå°è£
20     * @class   {nej.ut._$$EditorArea} å¯åªä½ç¼è¾å¨è¾å
¥åºå°è£
21     * @extends {nej.ut._$$Event}22     * @param   {Object} _options å¯éé
ç½®åæ°ï¼å·²å¤çåæ°å表å¦ä¸23     * @config  {Node|String|Function} parent  ç¶èç¹æè
ç¼è¾å¨å å
¥ç¶èç¹æ§è¡å½æ°24     * @config  {String}               style   ç¼è¾å¨åå§æ ·å¼25     * @config  {Boolean}              focus   æ¯å¦èªå¨èç¦26     * @config  {String}               content ææ¬å
容27     * 28     * [hr]29     * 30     * @event  {onselectionchange}31     */32    _p._$$EditorArea = NEJ.C();33    _pro = _p._$$EditorArea._$extend(_p._$$Event);34    /**35     * æ§ä»¶åå§å36     * @protected37     * @method {__init}38     * @return {Void}39     */40    _pro.__init = function(){41        this.__fopt = {42            visible:!0,43            onload:this.__onIFrameLoaded._$bind(this)44        };45        this.__supInit();46    };47    /**48     * æ§ä»¶éç½®49     * @protected50     * @method {__reset}51     * @param  {Object} å¯éé
ç½®åæ°52     * @return {Void}53     */54    _pro.__reset = (function(){55        var _cnttpl = '<head><base href="#<BSUL>"/><style>html,body{margin:0;padding:0;border:0;cursor:text;font-size:14px;font-family:Arial;word-wrap:break-word;}#<UDCS></style></head><body contenteditable="true"></body>';56        return function(_options){57            this.__supReset(_options);58            this.__focus = !!_options.focus;59            this.__content = _cnttpl60                .replace('#<UDCS>',_options.style||'')61                .replace('#<BSUL>',_options.base||location.href);62            this.__initcnt = _options.content||'';63            this.__fopt.parent = 64                _e._$get(_options.parent)||document.body;65            this.__iframe = _e._$createXFrame(this.__fopt);66        };67    })();68    /**69     * æ§ä»¶éæ¯70     * @protected71     * @method {__destroy}72     * @return {Void}73     */74    _pro.__destroy = function(){75        this.__supDestroy();76        _h.__clearRange(this._$getDocument());77        delete this.__content;78        delete this.__fopt.parent;79        delete this.__initcnt;80        this.__iframe = _e._$remove(this.__iframe);81    };82    /**83     * ä¿åéä¸ç¶æ84     * @protected85     * @method {__doSaveRange}86     * @return {Void}87     */88    _pro.__doSaveRange = function(){89        _h.__saveRange(this._$getDocument());90    };91    /**92     * iframeè½½å
¥å®æè§¦åäºä»¶93     * @protected94     * @method {__onIFrameLoaded}95     * @return {Void}96     */97    _pro.__onIFrameLoaded = function(_iframe){98        var _document = this._$getDocument();99        _document.open();100        _document.write(this.__content);101        if (location.hostname!=document.domain)102            _document.domain = document.domain;103        _document.close(); // <- will trigger iframe onload104        this.__doInitDomEvent([[105            _document,'click',106            this.__onDocumentClick._$bind(this)107        ],[108            _document,'selectionchange',109            this.__onSelectionChange._$bind(this)110        ],[111            _document,'beforedeactivate',112            this.__doSaveRange._$bind(this)113        ],[114            _document,'keydown',115            this.__onInputCheck._$bind(this)116        ],[117            _document,'mouseup',118            this.__onInputCheck._$bind(this)119        ],[120            _document,'paste',121            this.__onInputCheck._$bind(this)122        ],[123            _document,'drop',124            this.__onInputCheck._$bind(this)125        ]]);126        // init content and focus127        if (!!this.__initcnt){128            this._$setContent(this.__initcnt);129        }130        if (this.__focus){131            this._$focus();132            delete this.__focus;133        }134    };135    /**136     * ææ¡£ç¹å»äºä»¶137     * @protected138     * @method {__onDocumentClick}139     * @param  {Event} äºä»¶å¯¹è±¡140     * @return {Void}141     */142    _pro.__onDocumentClick = function(_event){143        _v._$dispatchEvent(document,'click');144    };145    /**146     * éä¸å
容åå触åäºä»¶147     * @protected148     * @method {__onSelectionChange}149     * @return {Void}150     */151    _pro.__onSelectionChange = function(){152        // TODO something153        this._$dispatchEvent('onselectionchange');154    };155    /**156     * è¾å
¥äºä»¶157     * @return {[type]} [description]158     */159    _pro.__onInputCheck = function(){160        if (!!this.__timer){161            window.clearTimeout(this.__timer);162        }163        this.__timer = window.setTimeout(164            this.__doCompareContent._$bind(this),100165        );166    };167    /**168     * æ¯è¾å¯ææ¬çå
容169     * @return {[type]} [description]170     */171    _pro.__doCompareContent = function(){172        var _document = this._$getDocument();173        if (!_document) return;174        var _content = _document.body.innerHTML;175        if (this.__initcnt!=_content){176            this.__initcnt = _content;177            this._$dispatchEvent('oninput',{178                cont:this._$getContent(),179                txt:this._$getTextContent()180            });181        }182    };183    /**184     * èç¦ç¼è¾å¨185     * @method {_$focus}186     * @param  {Number} å
æ ä½ç½®ï¼é»è®¤ä¸º0ï¼0-æ«å°¾ã1-èµ·å§ã2-ä¸å187     * @return {nej.ut._$$EditorArea}188     */189    _pro._$focus = function(_cursor){190        var _document = this._$getDocument();191        if (!_document) return this;192        _h.__focusRange(_document.body);193        _h.__moveCursorPosition(194            _document.body,195            parseInt(_cursor)||0196        );197        this.__onSelectionChange();198        return this;199    };200    /**201     * åç¼è¾å¨ææ¡£å¯¹è±¡202     * @method {_$getDocument}203     * @return {Node} ææ¡£å¯¹è±¡204     */205    _pro._$getDocument = function(){206        return this.__iframe.contentWindow.document;207    };208    /**209     * åç¼è¾å
容210     * @method {_$getContent}211     * @return {String} å
容212     */213    _pro._$getContent = function(_filter){214        var _document = this._$getDocument();215        _html = _h.__filterContent(!_document?'':_document.body.innerHTML);216        if(!_filter){217            _html = _h.__filterContentStyle(_html);218        }219        return !_h.__filterWordContent?_html:_h.__filterWordContent(_html);220    };221    /**222     * åçº¯ææ¬çç¼è¾å
容223     * @method {_$getTextContent}224     * @return {String} å
容225     */226    _pro._$getTextContent = function(){227        var _document = this._$getDocument(),228            _text = _document.body.innerText||229                    _document.body.textContent;230        return !_document?'':_text;231    };232    /**233     * 设置å
容234     * @method {_$setContent}235     * @param  {String} ç¼è¾å
容236     * @return {nej.ut._$$EditorArea}237     */238    _pro._$setContent = function(_content){239        var _document = this._$getDocument();240        if (!_document) return this;241        _document.body.innerHTML = _content;242        this.__onInputCheck();243        return this;244    };245    /**246     * æ§è¡ç¼è¾å½ä»¤247     * @method {_$execCommand}248     * @param  {String} å½ä»¤åç§°249     * @param  {String} å½ä»¤å¼250     * @param  {String} æ¯å¦éè¿styleçæ¹å¼æ¥æ¹åæ ·å¼ï¼æ¯å¦superscriptå½ä»¤251     * @return {nej.ut._$$EditorArea}252     */253    _pro._$execCommand = function(_command,_value,_css){254        var _document = this._$getDocument();255        if (!_document) return this;256        _h.__execCommand(_document,'styleWithCSS',false);257        _h.__execCommand(_document,_command,_value);258        this._$focus(2);259        this.__onInputCheck();260        return this;261    };262    /**263     * æ¥è¯¢å½ä»¤çç¶æ264     * @method {_$queryCommand}265     * @param  {String}   å½ä»¤åç§°266     * @param  {String}   æ¥è¯¢ç±»åï¼State/Enabled/Value267     * @return {Variable} æ¥è¯¢ç»æ268     */269    _pro._$queryCommand = function(_command,_type){270        var _document = this._$getDocument();271        return !_document ? null272               :_document['queryCommand'+_type](_command);273    };274    /**275     * è·åéä¸å
å®¹çææ¬276     * @method {_$getSelectText}277     * @return {String} ææ¬å
容278     */279    _pro._$getSelectText = function(){280        this._$focus(2);281        return _h.__getSelectText(this._$getDocument());282    };283    /**284     * è·åéæ©å
容çHTML285     * @method {_$getSelectHtml}286     * @return  {String} HTML代ç 287     */288    _pro._$getSelectHtml = function(){289        this._$focus(2);290        return _h.__getSelectHtml(this._$getDocument());291    };292    /**293     * åç¼è¾åºå容å¨ä½ç½®å¤§å°ä¿¡æ¯294     * @return {Object} ä½ç½®å¤§å°ä¿¡æ¯295     * [ntb]296     *  scrollTop     | æ»å¨åç´åç§»297     *  scrollLeft    | æ»å¨æ°´å¹³åç§»298     *  clientWidth   | 页é¢å¯è§å®½åº¦299     *  clientHeight  | 页é¢å¯è§é«åº¦300     *  scrollWidth   | 页颿»å¨å®½åº¦301     *  scrollHeight  | 页颿»å¨é«åº¦302     * [/ntb]303     */304    _pro._$getAreaBox = function(){305        var _document = this._$getDocument();306        return !_document?null:_e._$getPageBox(_document);307    };308};309NEJ.define(310    '{lib}util/editor/area.js',[311    '{lib}util/event.js',312    '{patch}editor.js'
...editor.js
Source: editor.js 
1/**2 * ------------------------------------------3 * 坿æ¬ç¼è¾å¨æ¥å£å®ç°æä»¶4 * @version  1.05 * @author   genify(caijf@corp.netease.com)6 * ------------------------------------------7 */8NEJ.define([9    'base/element',10    'base/platform'11],function(_e,_m,_p,_o,_f,_r){12    var __empty    = /(?:<(p|div)>(?:\ \;|<br\/?>)<\/\1>|<br\/?>|\ \;|\s)+$/gi, // empty content13        __reg_cls0 = /(?:class|lang)="(mso)?[^"]*"/gi,14        __reg_cls1 = /(?:class|lang)='(mso)?[^']*'/gi,15        __reg_cls2 = /(?:class|lang)=(mso)?[^>\s]*/gi,// IE7/8 hack16        __reg_ccm  = /(?:<!--)[^>]*(?:-->)/gi,17        __reg_st0  = /(?:<[^>]* style)="([^"]*)"/gi,18        __reg_st1  = /(?:<[^>]* style)='([^']*)'/gi,19        __reg_st2  = /(?:<[^>]* style)=([^>\s]*)/gi,// IE7/8 hack20        __reg_bgc  = /(?:background-color:|text-align:|color:)([^;]*)(;)*/gi;//clear class,lang21    /**22     * åèç¹æå¨ççªä½å¯¹è±¡23     * @param  {Node} _node èç¹24     * @return {Window}     çªä½25     */26    _p.__getWindow = function(_node){27        var _document = _p.__getDocument(_node);28        return _document.defaultView||_document.parentWindow||_document.window||_document;29    };30    /**31     * åèç¹å
³èçææ¡£å¯¹è±¡32     * @param  {Node} _node èç¹33     * @return {Document}   ææ¡£å¯¹è±¡34     */35    _p.__getDocument = function(_node){36        return _node.ownerDocument||_node;37    };38    /**39     * åéæ©åºå¯¹è±¡40     * @param  {Window} _window çªä½å¯¹è±¡41     * @return {DOMSelection}   éæ©åºå¯¹è±¡42     */43    _p.__getSelection = function(_window){44        if (!!_window.getSelection)45            return _window.getSelection();46        var _document = _window.document;47        if (!!_document.getSelection)48            return _document.getSelection();49        if (!!_document.selection)50            return _document.selection;51        return null;52    };53    /**54     * åéæ©åºèå´æä½å¯¹è±¡55     * @param  {Window} _window çªä½å¯¹è±¡56     * @return {Range}          èå´æä½å¯¹è±¡57     */58    _p.__getRange = function(_window){59        _window = _p.__getWindow(_window);60        var _selection = _p.__getSelection(_window);61        if (!_selection)62            return null;63        if (!!_selection.getRangeAt){64            return _selection.getRangeAt(0);65        }66        if (!!_selection.createRange)67            return _selection.createRange();68        return null;69    };70    /**71     * è·åéä¸å
å®¹çææ¬72     * @return {String} ææ¬å
容73     */74    _p.__getSelectText = function(_document){75        var _range = this.__getRange(_document);76        if (!_range) return '';77        return _range.toString()||_range.cloneContents().textContent||_range.commonAncestorContainer.data;78    };79    /**80     * è·åéä¸å
容çhtml81     * @param  {Object} _document82     * @return {String} éä¸å
容çhtml83     */84    _p.__getSelectHtml = function(_document){85        var _range = this.__getRange(_document);86        if (!_range) return '';87        var _ntmp = _e._$create('div');88        _ntmp.appendChild(_range.cloneContents());89        return _ntmp.innerHTML;90    };91    /**92     * è·åéä¸å
容çç¶èç¹93     * @param  {Object} _document94     * @return {Node|String} éä¸å
容çç¶èç¹95     */96    _p.__getSelectNode = (function(){97        var _checkNodeType = function(_node){98            if (_node.nodeType == 1){99                return _node;100            }else{101                _node = _node.parentNode;102                return _checkNodeType(_node);103            }104        };105        return function(_document){106            var _range = this.__getRange(_document),107                _node = _range.commonAncestorContainer||_range.parentElement();108            if (!_range || !_node) return '';109            return _checkNodeType(_node);110        };111    })();112    /**113     * ä¿åå½åéæ©ç¶æ114     * @param  {Node} _node èç¹115     * @return {Range}      èå´116     */117    _p.__saveRange = function(_node){118        // do nothing119    };120    /**121     * èç¦è³éä¸åºå122     * @param  {Node} _node èç¹123     * @return {Void}124     */125    _p.__focusRange = function(_node){126        _node.focus();127    };128    /**129     * æ¸
é¤éæ©ç¶æ130     * @param  {Node} _node èç¹131     * @return {Void}132     */133    _p.__clearRange = function(_node){134        // do nothing135    };136    /**137     * FFæ¯æselectionchange138     * @param  {[type]} _document [description]139     * @return {[type]}           [description]140     */141    _p.__supportSelectionChange = function(_document){142        // do nothing143    };144    /**145     * ç§»å¨å
æ è³èç¹çæå®ä½ç½®146     * @param  {Node}   _node     èç¹147     * @param  {Number} _position ä½ç½®ï¼0-æ«å°¾ã1-èµ·å§148     * @return {Void}149     */150    _p.__moveCursorPosition = (function(){151        var _fmap = [function(_node){return _node.childNodes.length;}152                    ,function(){return 0;}];153        return function(_node,_position){154            var _func = _fmap[_position];155            if (!_func){156                return;157            }158            _p.__getSelection(_p.__getWindow(_node))159            .collapse(_node,_func(_node));160        };161    })();162    /**163     * æ§è¡ç¼è¾å½ä»¤164     * @param  {Node}   _document ææ¡£å¯¹è±¡165     * @param  {String} _command  å½ä»¤åç§°166     * @param  {String} _value    å½ä»¤å¼167     * @return {Void}168     */169    _p.__execCommand = function(_document,_command,_value){170        if(_command == 'inserthtml'){171            this.__insertHtml(_document,_value);172            return;173        }174        _document.execCommand(_command,!1,_value);175    };176    /**177     * æå
¥htmlå½ä»¤å¤ç178     * @param {Object} _document ææ¡£å¯¹è±¡179     * @param {Object} _html180     */181    _p.__insertHtml = function(_document,_html){182        if (!document.selection){183            _document.execCommand('inserthtml',!1,_html);184            return;185        }186        var _range = _document.selection.createRange();187        if (!!_range.pasteHTML){_range.pasteHTML(_html);return;}188        _document.execCommand('delete',!1,null);189        _document.selection.createRange().pasteHTML(_html);190    };191    /**192     * å
å®¹åæ¥è¿æ»¤193     * @param {Object} _html194     */195    _p.__filterContent = function(_html,_keepClass){196        var _filterHTML;197        if (_keepClass){198            _filterHTML = (_html||'').replace(__empty,'').replace(__reg_ccm,'');199        }else{200            _filterHTML = (_html||'').replace(__empty,'').replace(__reg_cls0,'').replace(__reg_cls1,'').replace(__reg_cls2,'').replace(__reg_ccm,'');201        }202        _filterHTML = !_p.__filterContentPath?_filterHTML:_p.__filterContentPath(_filterHTML);203        return _filterHTML;204    };205    /**206     * è¿æ»¤é¤äºbackground-color以å¤çæææ ·å¼207     * @param  {[type]} _html [description]208     * @return {[type]}       [description]209     */210    _p.__filterContentStyle = (function(){211        var _regMap = { 0:/(?:<[^>]* style)="([^"]*)"/gi,212                        1:/(?:<[^>]* style)='([^']*)'/gi,213                        2:/(?:<[^>]* style)=([^>\s]*)/gi};214        var _doFilter = function(_reg,_html){215            _html = _html.replace(_regMap[_reg],function(_a,_b,_c){216                var _prefix = _a.split('style')[0];217                if(_b.match(__reg_bgc)!=null){218                    var _str0 = '';219                    var _bgc = _b.replace(__reg_bgc,function(_str,_sstr,_index){220                        return _str0 += _str;221                    }._$bind(this));222                    return _prefix + ' style="' + _str0 + '"';223                }else{224                    return _prefix;225                }226            }._$bind(this));227            return _html;228        };229        return function(_html){230            // IEå¤ç§æ
åµåæ¶åºç°231            _html = _doFilter(0,_html);232            _html = _doFilter(1,_html);233            _html = _doFilter(2,_html);234            return _html;235        };236    })();237    return _p;...Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4(async () => {5  const browser = await puppeteer.launch();6  const page = await browser.newPage();7  await page.pdf({path: 'google.pdf', format: 'A4'});8  await browser.close();9})();10const puppeteer = require('puppeteer');11const fs = require('fs');12const path = require('path');13(async () => {14  const browser = await puppeteer.launch();15  const page = await browser.newPage();16  await page.pdf({path: 'google.pdf', format: 'A4'});17  await browser.close();18})();19const puppeteer = require('puppeteer');20const fs = require('fs');21const path = require('path');22(async () => {23  const browser = await puppeteer.launch();24  const page = await browser.newPage();25  await page.pdf({path: 'google.pdf', format: 'A4'});26  await browser.close();27})();28const puppeteer = require('puppeteer');29const fs = require('fs');30const path = require('path');31(async () => {32  const browser = await puppeteer.launch();33  const page = await browser.newPage();34  await page.pdf({path: 'google.pdf', format: 'A4'});35  await browser.close();36})();37const puppeteer = require('puppeteer');38const fs = require('fs');39const path = require('path');40(async () => {41  const browser = await puppeteer.launch();42  const page = await browser.newPage();43  await page.pdf({path: 'google.pdf', format: 'A4'});44  await browser.close();45})();46const puppeteer = require('puppeteer');Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3  const browser = await puppeteer.launch({4  });5  const page = await browser.newPage();6  await page.pdf({path: 'test.pdf', format: 'A4'});7  await browser.close();8})();9import Document, { Html, Head, Main, NextScript } from 'next/document';10class MyDocument extends Document {11  static async getInitialProps(ctx) {12    const initialProps = await Document.getInitialProps(ctx);13    return { ...initialProps };14  }15  render() {16    return (17    );18  }19}20export default MyDocument;21import App from 'next/app';22import Head from 'next/head';23import { ThemeProvider } from 'styled-components';24import { GlobalStyle } from '../styles/global';25import theme from '../styles/theme';26class MyApp extends App {27  render() {28    const { Component, pageProps } = this.props;29    return (30        <ThemeProvider theme={theme}>31          <Component {...pageProps} />32    );33  }34}35export default MyApp;36import React from 'react';37const Index = () => {38  return (39  );40};41export default Index;42const colors = {43};44const theme = {45  fonts: {Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const writeFile = promisify(fs.writeFile);6const appendFile = promisify(fs.appendFile);7const unlinkFile = promisify(fs.unlink);8(async () => {9    const browser = await puppeteer.launch({ headless: true });10    const page = await browser.newPage();11    const html = await page.content();12    await writeFile(path.join(__dirname, 'google.html'), html);13    await appendFile(path.join(__dirname, 'google.html'), html);14    await unlinkFile(path.join(__dirname, 'google.html'));15    await browser.close();16})();Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3    const browser = await puppeteer.launch();4    const page = await browser.newPage();5    await page.pdf({path: 'google.pdf', format: 'A4'});6    await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10    const browser = await puppeteer.launch();11    const page = await browser.newPage();12    await page.pdf({path: 'google.pdf', format: 'A4'});13    await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17    const browser = await puppeteer.launch();18    const page = await browser.newPage();19    await page.pdf({path: 'google.pdf', format: 'A4'});20    await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24    const browser = await puppeteer.launch();25    const page = await browser.newPage();26    await page.pdf({path: 'google.pdf', format: 'A4'});27    await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31    const browser = await puppeteer.launch();32    const page = await browser.newPage();33    await page.pdf({path: 'google.pdf', format: 'A4'});34    await browser.close();35})();36const puppeteer = require('puppeteer');37(async () => {38    const browser = await puppeteer.launch();39    const page = await browser.newPage();40    await page.goto('/tmp/chromium: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory Vercel
Puppeteer Get all data attribute values
How to click element using x/y coordinates with puppeteer?
Puppeteer will not open chrome (getting error)
Puppeteer opening chrome instance for each file at once
How to click on specific part of element puppeteer
UnhandledPromiseRejectionWarning: ReferenceError: browser is not defined when running puppeteer?
How do I call function outside async function in puppeteer with nodeJS
How to pass a function in Puppeteers .evaluate() method
Puppeteer loads blank page with 429 when accessing URL
I had the same issue where puppeteer was running okay on my local environment but when i deployed to AWS EC2 i face up the same error shared loading libraries Solution
The most common cause is a bug in Node.js v14.0.0 which broke extract-zip, the module Puppeteer uses to extract browser downloads into the right place. The bug was fixed in Node.js v14.1.0, so please make sure you're running that version or higher. Alternatively, if you cannot upgrade, you could downgrade to Node.js v12, but we recommend upgrading when possible.
For those who might have experience this issue while running on windows enviroment, You can try to pass ignoreDefaultArgs: ['--disable-extensions'] option when launching it chromium from code i.e
const browser = await puppeteer.launch({ignoreDefaultArgs: ['--disable-extensions']})
This will deactivate default behaviour of puppeteer from disabling any extensions usually used by chromium/chrome.
Linux and MAcOS uses
The issues that results in this error
UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process! error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory TROUBLESHOOTING
is mostly but not all the times caused by missing dependencies that are required in the latest version. The good thing is you can easily check the missing chrome dependencies causing the crash.
- cd /project_folder/node_modules/puppeteer/.local-chromium/linux-some number/chrome-linux
 
replace the linux-some number with whatever ls will output- ls at /.local-chromium to check name of your directory
 
At the last directory [ chrome-linux ] run below command to check the missing dependencies
ldd chrome | grep not
if you see any missing dependencies, run this command to install everything and restart your application.
sudo apt-get install ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils
Voila!! everything should be fixed
Check out the latest blogs from LambdaTest on this topic:
We were eager to listen to Manoj Kumar, VP Developer Relations, LambdaTest, speak on the importance of Selenium 4.0 and how bright the future is. This was the agenda of the speech:
Testing a product is a learning process – Brian Marick
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on WebDriverIO Tutorial and Selenium JavaScript Tutorial.
Playwright is a framework that I’ve always heard great things about but never had a chance to pick up until earlier this year. And since then, it’s become one of my favorite test automation frameworks to use when building a new automation project. It’s easy to set up, feature-packed, and one of the fastest, most reliable frameworks I’ve worked with.
JavaScript is one of the most widely used programming languages. This popularity invites a lot of JavaScript development and testing frameworks to ease the process of working with it. As a result, numerous JavaScript testing frameworks can be used to perform unit testing.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
