├── .gitignore ├── icons ├── 32.png ├── 48.png ├── 96.png └── 32-dev.png ├── README.md ├── .idea ├── .gitignore ├── vcs.xml ├── misc.xml ├── modules.xml └── inspectionProfiles │ └── Project_Default.xml ├── trilium-web-clipper.iml ├── bin ├── release-firefox.sh ├── release-chrome.sh └── release.sh ├── popup ├── popup.css ├── popup.html └── popup.js ├── utils.js ├── manifest.json ├── options ├── options.html └── options.js ├── lib ├── Readability-readerable.js ├── toast.js ├── cash.min.js ├── JSDOMParser.js └── browser-polyfill.js ├── trilium_server_facade.js ├── content.js ├── background.js └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | dist/ -------------------------------------------------------------------------------- /icons/32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TriliumNext/web-clipper/HEAD/icons/32.png -------------------------------------------------------------------------------- /icons/48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TriliumNext/web-clipper/HEAD/icons/48.png -------------------------------------------------------------------------------- /icons/96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TriliumNext/web-clipper/HEAD/icons/96.png -------------------------------------------------------------------------------- /icons/32-dev.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TriliumNext/web-clipper/HEAD/icons/32-dev.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Integrated as part of the [TriliumNext monorepo](https://github.com/TriliumNext/Notes). 2 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml 3 | 4 | # Datasource local storage ignored files 5 | /dataSources.local.xml -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /trilium-web-clipper.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | -------------------------------------------------------------------------------- /bin/release-firefox.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | WEB_EXT_ID="{1410742d-b377-40e7-a9db-63dc9c6ec99c}" 5 | 6 | ARTIFACT_NAME=trilium-web-clipper-firefox 7 | BUILD_DIR=dist/$ARTIFACT_NAME 8 | 9 | rm -rf "$BUILD_DIR" 10 | mkdir -p "$BUILD_DIR" 11 | 12 | cp -r icons lib options popup *.js manifest.json "$BUILD_DIR" 13 | 14 | cd dist/"${ARTIFACT_NAME}" || exit 15 | 16 | jq '.name = "Trilium Web Clipper"' manifest.json | sponge manifest.json 17 | 18 | web-ext sign --api-key $FIREFOX_API_KEY --api-secret $FIREFOX_API_SECRET --artifacts-dir ../ 19 | 20 | cd .. 21 | rm -r "${ARTIFACT_NAME}" 22 | -------------------------------------------------------------------------------- /popup/popup.css: -------------------------------------------------------------------------------- 1 | body { 2 | width: 300px; 3 | font-size: 12px; 4 | font-family: sans-serif; 5 | } 6 | 7 | .button { 8 | margin: 3% auto; 9 | padding: 4px; 10 | text-align: center; 11 | border: 1px solid #ccc; 12 | border-radius: 3px; 13 | background-color: #eee; 14 | cursor: pointer; 15 | color: black; 16 | } 17 | 18 | .wide { 19 | min-width: 8em; 20 | } 21 | 22 | .full { 23 | display: block; 24 | width: 100%; 25 | } 26 | 27 | #save-link-with-note-wrapper { 28 | display: none; 29 | } 30 | 31 | #save-link-with-note-textarea { 32 | width: 100%; 33 | } 34 | 35 | #save-button { 36 | border-color: #0062cc; 37 | background-color: #0069d9; 38 | color: white; 39 | } 40 | 41 | #check-connection-button { 42 | float: right; 43 | margin-top: -6px; 44 | } 45 | 46 | button[disabled] { 47 | color: #aaa; 48 | } 49 | -------------------------------------------------------------------------------- /utils.js: -------------------------------------------------------------------------------- 1 | function randomString(len) { 2 | let text = ""; 3 | const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 4 | 5 | for (let i = 0; i < len; i++) { 6 | text += possible.charAt(Math.floor(Math.random() * possible.length)); 7 | } 8 | 9 | return text; 10 | } 11 | 12 | function getBaseUrl() { 13 | let output = getPageLocationOrigin() + location.pathname; 14 | 15 | if (output[output.length - 1] !== '/') { 16 | output = output.split('/'); 17 | output.pop(); 18 | output = output.join('/'); 19 | } 20 | 21 | return output; 22 | } 23 | 24 | function getPageLocationOrigin() { 25 | // location.origin normally returns the protocol + domain + port (eg. https://example.com:8080) 26 | // but for file:// protocol this is browser dependant and in particular Firefox returns "null" in this case. 27 | return location.protocol === 'file:' ? 'file://' : location.origin; 28 | } 29 | -------------------------------------------------------------------------------- /bin/release-chrome.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | VERSION=$(jq -r ".version" manifest.json) 5 | CHROME_EXTENSION_ID=dfhgmnfclbebfobmblelddiejjcijbjm 6 | 7 | BUILD_DIR=trilium-web-clipper-chrome 8 | 9 | rm -rf "dist/$BUILD_DIR" 10 | mkdir -p "dist/$BUILD_DIR" 11 | 12 | cp -r icons lib options popup *.js manifest.json "dist/$BUILD_DIR" 13 | 14 | cd dist/"${BUILD_DIR}" || exit 15 | 16 | jq '.name = "Trilium Web Clipper"' manifest.json | sponge manifest.json 17 | jq 'del(.browser_specific_settings)' manifest.json | sponge manifest.json 18 | 19 | EXT_FILE_NAME=trilium_web_clipper-${VERSION}-chrome.zip 20 | 21 | zip -r ../${EXT_FILE_NAME} * 22 | 23 | cd .. 24 | rm -r "${BUILD_DIR}" 25 | 26 | # https://github.com/fregante/chrome-webstore-upload-cli 27 | chrome-webstore-upload upload --source ${EXT_FILE_NAME} --auto-publish --extension-id "${CHROME_EXTENSION_ID}" --client-id "${CHROME_CLIENT_ID}" --client-secret "${CHROME_CLIENT_SECRET}" --refresh-token "${CHROME_REFRESH_TOKEN}" 28 | 29 | -------------------------------------------------------------------------------- /bin/release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | 4 | export GITHUB_REPO=trilium-web-clipper 5 | 6 | if [[ $# -eq 0 ]] ; then 7 | echo "Missing argument of new version" 8 | exit 1 9 | fi 10 | 11 | VERSION=$1 12 | 13 | if ! [[ ${VERSION} =~ ^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}(-.+)?$ ]] ; 14 | then 15 | echo "Version ${VERSION} isn't in format X.Y.Z" 16 | exit 1 17 | fi 18 | 19 | if ! git diff-index --quiet HEAD --; then 20 | echo "There are uncommitted changes" 21 | exit 1 22 | fi 23 | 24 | echo "Releasing Trilium Web Clipper $VERSION" 25 | 26 | jq '.version = "'"$VERSION"'"' manifest.json | sponge manifest.json 27 | 28 | git add manifest.json 29 | 30 | echo 'module.exports = { buildDate:"'$(date --iso-8601=seconds)'", buildRevision: "'$(git log -1 --format="%H")'" };' > build.js 31 | 32 | git add build.js 33 | 34 | TAG=v$VERSION 35 | 36 | echo "Committing package.json version change" 37 | 38 | git commit -m "release $VERSION" 39 | git push 40 | 41 | echo "Tagging commit with $TAG" 42 | 43 | git tag "$TAG" 44 | git push origin "$TAG" 45 | 46 | bin/release-firefox.sh 47 | bin/release-chrome.sh 48 | 49 | FIREFOX_BUILD=trilium_web_clipper-$VERSION-an+fx.xpi 50 | CHROME_BUILD=trilium_web_clipper-${VERSION}-chrome.zip 51 | 52 | echo "Creating release in GitHub" 53 | 54 | github-release release \ 55 | --tag "$TAG" \ 56 | --name "$TAG release" 57 | 58 | echo "Uploading firefox build package" 59 | 60 | github-release upload \ 61 | --tag "$TAG" \ 62 | --name "$FIREFOX_BUILD" \ 63 | --file "dist/$FIREFOX_BUILD" 64 | 65 | echo "Uploading chrome build package" 66 | 67 | github-release upload \ 68 | --tag "$TAG" \ 69 | --name "$CHROME_BUILD" \ 70 | --file "dist/$CHROME_BUILD" 71 | 72 | echo "Release finished!" 73 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "Trilium Web Clipper (dev)", 4 | "version": "1.0.1", 5 | "description": "Save web clippings to Trilium Notes.", 6 | "homepage_url": "https://github.com/zadam/trilium-web-clipper", 7 | "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'", 8 | "icons": { 9 | "32": "icons/32.png", 10 | "48": "icons/48.png", 11 | "96": "icons/96.png" 12 | }, 13 | "permissions": [ 14 | "activeTab", 15 | "tabs", 16 | "http://*/", 17 | "https://*/", 18 | "", 19 | "storage", 20 | "contextMenus" 21 | ], 22 | "browser_action": { 23 | "default_icon": "icons/32.png", 24 | "default_title": "Trilium Web Clipper", 25 | "default_popup": "popup/popup.html" 26 | }, 27 | "content_scripts": [ 28 | { 29 | "matches": [ 30 | "" 31 | ], 32 | "js": [ 33 | "lib/browser-polyfill.js", 34 | "utils.js", 35 | "content.js" 36 | ] 37 | } 38 | ], 39 | "background": { 40 | "scripts": [ 41 | "lib/browser-polyfill.js", 42 | "utils.js", 43 | "trilium_server_facade.js", 44 | "background.js" 45 | ] 46 | }, 47 | "options_ui": { 48 | "page": "options/options.html" 49 | }, 50 | "commands": { 51 | "saveSelection": { 52 | "description": "Save the selected text into a note", 53 | "suggested_key": { 54 | "default": "Ctrl+Shift+S" 55 | } 56 | }, 57 | "saveWholePage": { 58 | "description": "Save the current page", 59 | "suggested_key": { 60 | "default": "Alt+Shift+S" 61 | } 62 | }, 63 | "saveCroppedScreenshot": { 64 | "description": "Take a cropped screenshot of the current page", 65 | "suggested_key": { 66 | "default": "Ctrl+Shift+E" 67 | } 68 | } 69 | }, 70 | "browser_specific_settings": { 71 | "gecko": { 72 | "id": "{1410742d-b377-40e7-a9db-63dc9c6ec99c}" 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /popup/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 |

Trilium Web Clipper

13 | 14 | 15 |
16 | 17 | 18 | 19 |
20 |
21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 42 | 43 |
44 | 45 | 46 |
Status: unknown
47 |
48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /options/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |

Trilium desktop instance

15 | 16 |

Web clipper by default tries to find a running desktop instance on port 37740. If you configured your Trilium desktop app to run on a different port, you can specify it here (otherwise keep it empty).

17 | 18 |
19 |

20 | 21 | 22 | (normally keep this empty) 23 |

24 | 25 | 26 |
27 | 28 |

Trilium server instance

29 | 30 |

If you have a server instance set up, you can optionally configure it as a fail over target for the clipped notes. Desktop instance will still be given priority, but in cases that the desktop instance is not available (e.g. it's not running), web clipper will send the notes to the server instance instead.

31 | 32 | 37 | 38 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /options/options.js: -------------------------------------------------------------------------------- 1 | const $triliumServerUrl = $("#trilium-server-url"); 2 | const $triliumServerPassword = $("#trilium-server-password"); 3 | 4 | const $errorMessage = $("#error-message"); 5 | const $successMessage = $("#success-message"); 6 | 7 | function showError(message) { 8 | $errorMessage.html(message).show(); 9 | $successMessage.hide(); 10 | } 11 | 12 | function showSuccess(message) { 13 | $successMessage.html(message).show(); 14 | $errorMessage.hide(); 15 | } 16 | 17 | async function saveTriliumServerSetup(e) { 18 | e.preventDefault(); 19 | 20 | if ($triliumServerUrl.val().trim().length === 0 21 | || $triliumServerPassword.val().trim().length === 0) { 22 | showError("One or more mandatory inputs are missing. Please fill in server URL and password."); 23 | 24 | return; 25 | } 26 | 27 | let resp; 28 | 29 | try { 30 | resp = await fetch($triliumServerUrl.val() + '/api/login/token', { 31 | method: "POST", 32 | headers: { 33 | 'Accept': 'application/json', 34 | 'Content-Type': 'application/json' 35 | }, 36 | body: JSON.stringify({ 37 | password: $triliumServerPassword.val() 38 | }) 39 | }); 40 | } 41 | catch (e) { 42 | showError("Unknown error: " + e.message); 43 | return; 44 | } 45 | 46 | if (resp.status === 401) { 47 | showError("Incorrect credentials."); 48 | } 49 | else if (resp.status !== 200) { 50 | showError("Unrecognised response with status code " + resp.status); 51 | } 52 | else { 53 | const json = await resp.json(); 54 | 55 | showSuccess("Authentication against Trilium server has been successful."); 56 | 57 | $triliumServerPassword.val(''); 58 | 59 | browser.storage.sync.set({ 60 | triliumServerUrl: $triliumServerUrl.val(), 61 | authToken: json.token 62 | }); 63 | 64 | await restoreOptions(); 65 | } 66 | } 67 | 68 | const $triliumServerSetupForm = $("#trilium-server-setup-form"); 69 | const $triliumServerConfiguredDiv = $("#trilium-server-configured"); 70 | const $triliumServerLink = $("#trilium-server-link"); 71 | const $resetTriliumServerSetupLink = $("#reset-trilium-server-setup"); 72 | 73 | $resetTriliumServerSetupLink.on("click", e => { 74 | e.preventDefault(); 75 | 76 | browser.storage.sync.set({ 77 | triliumServerUrl: '', 78 | authToken: '' 79 | }); 80 | 81 | restoreOptions(); 82 | }); 83 | 84 | $triliumServerSetupForm.on("submit", saveTriliumServerSetup); 85 | 86 | const $triliumDesktopPort = $("#trilium-desktop-port"); 87 | const $triilumDesktopSetupForm = $("#trilium-desktop-setup-form"); 88 | 89 | $triilumDesktopSetupForm.on("submit", e => { 90 | e.preventDefault(); 91 | 92 | const port = $triliumDesktopPort.val().trim(); 93 | const portNum = parseInt(port); 94 | 95 | if (port && (isNaN(portNum) || portNum <= 0 || portNum >= 65536)) { 96 | showError(`Please enter valid port number.`); 97 | return; 98 | } 99 | 100 | browser.storage.sync.set({ 101 | triliumDesktopPort: port 102 | }); 103 | 104 | showSuccess(`Port number has been saved.`); 105 | }); 106 | 107 | async function restoreOptions() { 108 | const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl"); 109 | const {authToken} = await browser.storage.sync.get("authToken"); 110 | 111 | $errorMessage.hide(); 112 | $successMessage.hide(); 113 | 114 | $triliumServerUrl.val(''); 115 | $triliumServerPassword.val(''); 116 | 117 | if (triliumServerUrl && authToken) { 118 | $triliumServerSetupForm.hide(); 119 | $triliumServerConfiguredDiv.show(); 120 | 121 | $triliumServerLink 122 | .attr("href", triliumServerUrl) 123 | .text(triliumServerUrl); 124 | } 125 | else { 126 | $triliumServerSetupForm.show(); 127 | $triliumServerConfiguredDiv.hide(); 128 | } 129 | 130 | const {triliumDesktopPort} = await browser.storage.sync.get("triliumDesktopPort"); 131 | 132 | $triliumDesktopPort.val(triliumDesktopPort); 133 | } 134 | 135 | $(restoreOptions); 136 | -------------------------------------------------------------------------------- /lib/Readability-readerable.js: -------------------------------------------------------------------------------- 1 | /* eslint-env es6:false */ 2 | /* 3 | * Copyright (c) 2010 Arc90 Inc 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | /* 19 | * This code is heavily based on Arc90's readability.js (1.7.1) script 20 | * available at: http://code.google.com/p/arc90labs-readability 21 | */ 22 | 23 | var REGEXPS = { 24 | // NOTE: These two regular expressions are duplicated in 25 | // Readability.js. Please keep both copies in sync. 26 | unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, 27 | okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i, 28 | }; 29 | 30 | function isNodeVisible(node) { 31 | // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes. 32 | return (!node.style || node.style.display != "none") 33 | && !node.hasAttribute("hidden") 34 | //check for "fallback-image" so that wikimedia math images are displayed 35 | && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1)); 36 | } 37 | 38 | /** 39 | * Decides whether or not the document is reader-able without parsing the whole thing. 40 | * @param {Object} options Configuration object. 41 | * @param {number} [options.minContentLength=140] The minimum node content length used to decide if the document is readerable. 42 | * @param {number} [options.minScore=20] The minumum cumulated 'score' used to determine if the document is readerable. 43 | * @param {Function} [options.visibilityChecker=isNodeVisible] The function used to determine if a node is visible. 44 | * @return {boolean} Whether or not we suspect Readability.parse() will suceeed at returning an article object. 45 | */ 46 | function isProbablyReaderable(doc, options = {}) { 47 | // For backward compatibility reasons 'options' can either be a configuration object or the function used 48 | // to determine if a node is visible. 49 | if (typeof options == "function") { 50 | options = { visibilityChecker: options }; 51 | } 52 | 53 | var defaultOptions = { minScore: 20, minContentLength: 140, visibilityChecker: isNodeVisible }; 54 | options = Object.assign(defaultOptions, options); 55 | 56 | var nodes = doc.querySelectorAll("p, pre, article"); 57 | 58 | // Get
nodes which have
node(s) and append them into the `nodes` variable. 59 | // Some articles' DOM structures might look like 60 | //
61 | // Sentences
62 | //
63 | // Sentences
64 | //
65 | var brNodes = doc.querySelectorAll("div > br"); 66 | if (brNodes.length) { 67 | var set = new Set(nodes); 68 | [].forEach.call(brNodes, function (node) { 69 | set.add(node.parentNode); 70 | }); 71 | nodes = Array.from(set); 72 | } 73 | 74 | var score = 0; 75 | // This is a little cheeky, we use the accumulator 'score' to decide what to return from 76 | // this callback: 77 | return [].some.call(nodes, function (node) { 78 | if (!options.visibilityChecker(node)) { 79 | return false; 80 | } 81 | 82 | var matchString = node.className + " " + node.id; 83 | if (REGEXPS.unlikelyCandidates.test(matchString) && 84 | !REGEXPS.okMaybeItsACandidate.test(matchString)) { 85 | return false; 86 | } 87 | 88 | if (node.matches("li p")) { 89 | return false; 90 | } 91 | 92 | var textContentLength = node.textContent.trim().length; 93 | if (textContentLength < options.minContentLength) { 94 | return false; 95 | } 96 | 97 | score += Math.sqrt(textContentLength - options.minContentLength); 98 | 99 | if (score > options.minScore) { 100 | return true; 101 | } 102 | return false; 103 | }); 104 | } 105 | 106 | if (typeof module === "object") { 107 | module.exports = isProbablyReaderable; 108 | } 109 | -------------------------------------------------------------------------------- /popup/popup.js: -------------------------------------------------------------------------------- 1 | async function sendMessage(message) { 2 | try { 3 | return await browser.runtime.sendMessage(message); 4 | } 5 | catch (e) { 6 | console.log("Calling browser runtime failed:", e); 7 | 8 | alert("Calling browser runtime failed. Refreshing page might help."); 9 | } 10 | } 11 | 12 | const $showOptionsButton = $("#show-options-button"); 13 | const $saveCroppedScreenShotButton = $("#save-cropped-screenshot-button"); 14 | const $saveWholeScreenShotButton = $("#save-whole-screenshot-button"); 15 | const $saveWholePageButton = $("#save-whole-page-button"); 16 | const $saveTabsButton = $("#save-tabs-button"); 17 | 18 | $showOptionsButton.on("click", () => browser.runtime.openOptionsPage()); 19 | 20 | $saveCroppedScreenShotButton.on("click", () => { 21 | sendMessage({name: 'save-cropped-screenshot'}); 22 | 23 | window.close(); 24 | }); 25 | 26 | $saveWholeScreenShotButton.on("click", () => { 27 | sendMessage({name: 'save-whole-screenshot'}); 28 | 29 | window.close(); 30 | }); 31 | 32 | $saveWholePageButton.on("click", () => sendMessage({name: 'save-whole-page'})); 33 | 34 | $saveTabsButton.on("click", () => sendMessage({name: 'save-tabs'})); 35 | 36 | const $saveLinkWithNoteWrapper = $("#save-link-with-note-wrapper"); 37 | const $textNote = $("#save-link-with-note-textarea"); 38 | const $keepTitle = $("#keep-title-checkbox"); 39 | 40 | $textNote.on('keypress', function (event) { 41 | if ((event.which === 10 || event.which === 13) && event.ctrlKey) { 42 | saveLinkWithNote(); 43 | return false; 44 | } 45 | 46 | return true; 47 | }); 48 | 49 | $("#save-link-with-note-button").on("click", () => { 50 | $saveLinkWithNoteWrapper.show(); 51 | 52 | $textNote[0].focus(); 53 | }); 54 | 55 | $("#cancel-button").on("click", () => { 56 | $saveLinkWithNoteWrapper.hide(); 57 | $textNote.val(""); 58 | 59 | window.close(); 60 | }); 61 | 62 | async function saveLinkWithNote() { 63 | const textNoteVal = $textNote.val().trim(); 64 | let title, content; 65 | 66 | if (!textNoteVal) { 67 | title = ''; 68 | content = ''; 69 | } 70 | else if ($keepTitle[0].checked){ 71 | title = ''; 72 | content = textNoteVal; 73 | } 74 | else { 75 | const match = /^(.*?)([.?!]\s|\n)/.exec(textNoteVal); 76 | 77 | if (match) { 78 | title = match[0].trim(); 79 | content = textNoteVal.substr(title.length).trim(); 80 | } 81 | else { 82 | title = textNoteVal; 83 | content = ''; 84 | } 85 | } 86 | 87 | content = escapeHtml(content); 88 | 89 | const result = await sendMessage({name: 'save-link-with-note', title, content}); 90 | 91 | if (result) { 92 | $textNote.val(''); 93 | 94 | window.close(); 95 | } 96 | } 97 | 98 | $("#save-button").on("click", saveLinkWithNote); 99 | 100 | $("#show-help-button").on("click", () => { 101 | window.open("https://github.com/zadam/trilium/wiki/Web-clipper", '_blank'); 102 | }); 103 | 104 | function escapeHtml(string) { 105 | const pre = document.createElement('pre'); 106 | const text = document.createTextNode(string); 107 | pre.appendChild(text); 108 | 109 | const htmlWithPars = pre.innerHTML.replace(/\n/g, "

"); 110 | 111 | return '

' + htmlWithPars + '

'; 112 | } 113 | 114 | const $connectionStatus = $("#connection-status"); 115 | const $needsConnection = $(".needs-connection"); 116 | const $alreadyVisited = $("#already-visited"); 117 | 118 | browser.runtime.onMessage.addListener(request => { 119 | if (request.name === 'trilium-search-status') { 120 | const {triliumSearch} = request; 121 | 122 | let statusText = triliumSearch.status; 123 | let isConnected; 124 | 125 | if (triliumSearch.status === 'not-found') { 126 | statusText = `Not found`; 127 | isConnected = false; 128 | } 129 | else if (triliumSearch.status === 'version-mismatch') { 130 | const whatToUpgrade = triliumSearch.extensionMajor > triliumSearch.triliumMajor ? "Trilium Notes" : "this extension"; 131 | 132 | statusText = `Trilium instance found, but it is not compatible with this extension version. Please update ${whatToUpgrade} to the latest version.`; 133 | isConnected = true; 134 | } 135 | else if (triliumSearch.status === 'found-desktop') { 136 | statusText = `Connected on port ${triliumSearch.port}`; 137 | isConnected = true; 138 | } 139 | else if (triliumSearch.status === 'found-server') { 140 | statusText = `Connected to the server`; 141 | isConnected = true; 142 | } 143 | 144 | $connectionStatus.html(statusText); 145 | 146 | if (isConnected) { 147 | $needsConnection.removeAttr("disabled"); 148 | $needsConnection.removeAttr("title"); 149 | browser.runtime.sendMessage({name: "trigger-trilium-search-note-url"}); 150 | } 151 | else { 152 | $needsConnection.attr("disabled", "disabled"); 153 | $needsConnection.attr("title", "This action can't be performed without active connection to Trilium."); 154 | } 155 | } 156 | else if (request.name == "trilium-previously-visited"){ 157 | const {searchNote} = request; 158 | if (searchNote.status === 'found'){ 159 | const a = createLink({name: 'openNoteInTrilium', noteId: searchNote.noteId}, 160 | "Open in Trilium.") 161 | noteFound = `Already visited website!`; 162 | $alreadyVisited.html(noteFound); 163 | $alreadyVisited[0].appendChild(a); 164 | }else{ 165 | $alreadyVisited.html(''); 166 | } 167 | 168 | 169 | } 170 | }); 171 | 172 | const $checkConnectionButton = $("#check-connection-button"); 173 | 174 | $checkConnectionButton.on("click", () => { 175 | browser.runtime.sendMessage({ 176 | name: "trigger-trilium-search" 177 | }) 178 | }); 179 | 180 | $(() => browser.runtime.sendMessage({name: "send-trilium-search-status"})); 181 | -------------------------------------------------------------------------------- /trilium_server_facade.js: -------------------------------------------------------------------------------- 1 | const PROTOCOL_VERSION_MAJOR = 1; 2 | 3 | function isDevEnv() { 4 | const manifest = browser.runtime.getManifest(); 5 | 6 | return manifest.name.endsWith('(dev)'); 7 | } 8 | 9 | class TriliumServerFacade { 10 | constructor() { 11 | this.triggerSearchForTrilium(); 12 | 13 | // continually scan for changes (if e.g. desktop app is started after browser) 14 | setInterval(() => this.triggerSearchForTrilium(), 60 * 1000); 15 | } 16 | 17 | async sendTriliumSearchStatusToPopup() { 18 | try { 19 | await browser.runtime.sendMessage({ 20 | name: "trilium-search-status", 21 | triliumSearch: this.triliumSearch 22 | }); 23 | } 24 | catch (e) {} // nothing might be listening 25 | } 26 | async sendTriliumSearchNoteToPopup(){ 27 | try{ 28 | await browser.runtime.sendMessage({ 29 | name: "trilium-previously-visited", 30 | searchNote: this.triliumSearchNote 31 | }) 32 | 33 | } 34 | catch (e) {} // nothing might be listening 35 | } 36 | 37 | setTriliumSearchNote(st){ 38 | this.triliumSearchNote = st; 39 | this.sendTriliumSearchNoteToPopup(); 40 | } 41 | 42 | setTriliumSearch(ts) { 43 | this.triliumSearch = ts; 44 | 45 | this.sendTriliumSearchStatusToPopup(); 46 | } 47 | 48 | setTriliumSearchWithVersionCheck(json, resp) { 49 | const [major, minor] = json.protocolVersion 50 | .split(".") 51 | .map(chunk => parseInt(chunk)); 52 | 53 | // minor version is intended to be used to dynamically limit features provided by extension 54 | // if some specific Trilium API is not supported. So far not needed. 55 | 56 | if (major !== PROTOCOL_VERSION_MAJOR) { 57 | this.setTriliumSearch({ 58 | status: 'version-mismatch', 59 | extensionMajor: PROTOCOL_VERSION_MAJOR, 60 | triliumMajor: major 61 | }); 62 | } 63 | else { 64 | this.setTriliumSearch(resp); 65 | } 66 | } 67 | 68 | async triggerSearchForTrilium() { 69 | this.setTriliumSearch({ status: 'searching' }); 70 | 71 | try { 72 | const port = await this.getPort(); 73 | 74 | console.debug('Trying port ' + port); 75 | 76 | const resp = await fetch(`http://127.0.0.1:${port}/api/clipper/handshake`); 77 | 78 | const text = await resp.text(); 79 | 80 | console.log("Received response:", text); 81 | 82 | const json = JSON.parse(text); 83 | 84 | if (json.appName === 'trilium') { 85 | this.setTriliumSearchWithVersionCheck(json, { 86 | status: 'found-desktop', 87 | port: port, 88 | url: 'http://127.0.0.1:' + port 89 | }); 90 | 91 | return; 92 | } 93 | } 94 | catch (error) { 95 | // continue 96 | } 97 | 98 | const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl"); 99 | const {authToken} = await browser.storage.sync.get("authToken"); 100 | 101 | if (triliumServerUrl && authToken) { 102 | try { 103 | const resp = await fetch(triliumServerUrl + '/api/clipper/handshake', { 104 | headers: { 105 | Authorization: authToken 106 | } 107 | }); 108 | 109 | const text = await resp.text(); 110 | 111 | console.log("Received response:", text); 112 | 113 | const json = JSON.parse(text); 114 | 115 | if (json.appName === 'trilium') { 116 | this.setTriliumSearchWithVersionCheck(json, { 117 | status: 'found-server', 118 | url: triliumServerUrl, 119 | token: authToken 120 | }); 121 | 122 | return; 123 | } 124 | } 125 | catch (e) { 126 | console.log("Request to the configured server instance failed with:", e); 127 | } 128 | } 129 | 130 | // if all above fails it's not found 131 | this.setTriliumSearch({ status: 'not-found' }); 132 | } 133 | 134 | async triggerSearchNoteByUrl(noteUrl) { 135 | const resp = await triliumServerFacade.callService('GET', 'notes-by-url/' + encodeURIComponent(noteUrl)) 136 | let newStatus = { 137 | status: 'not-found', 138 | noteId: null 139 | } 140 | if (resp && resp.noteId) { 141 | newStatus.noteId = resp.noteId; 142 | newStatus.status = 'found'; 143 | } 144 | this.setTriliumSearchNote(newStatus); 145 | } 146 | async waitForTriliumSearch() { 147 | return new Promise((res, rej) => { 148 | const checkStatus = () => { 149 | if (this.triliumSearch.status === "searching") { 150 | setTimeout(checkStatus, 500); 151 | } 152 | else if (this.triliumSearch.status === 'not-found') { 153 | rej(new Error("Trilium instance has not been found.")); 154 | } 155 | else { 156 | res(); 157 | } 158 | }; 159 | 160 | checkStatus(); 161 | }); 162 | } 163 | 164 | async getPort() { 165 | const {triliumDesktopPort} = await browser.storage.sync.get("triliumDesktopPort"); 166 | 167 | if (triliumDesktopPort) { 168 | return parseInt(triliumDesktopPort); 169 | } 170 | else { 171 | return isDevEnv() ? 37740 : 37840; 172 | } 173 | } 174 | 175 | async callService(method, path, body) { 176 | const fetchOptions = { 177 | method: method, 178 | headers: { 179 | 'Content-Type': 'application/json' 180 | }, 181 | }; 182 | 183 | if (body) { 184 | fetchOptions.body = typeof body === 'string' ? body : JSON.stringify(body); 185 | } 186 | 187 | try { 188 | await this.waitForTriliumSearch(); 189 | 190 | fetchOptions.headers.Authorization = this.triliumSearch.token || ""; 191 | fetchOptions.headers['trilium-local-now-datetime'] = this.localNowDateTime(); 192 | 193 | const url = this.triliumSearch.url + "/api/clipper/" + path; 194 | 195 | console.log(`Sending ${method} request to ${url}`); 196 | 197 | const response = await fetch(url, fetchOptions); 198 | 199 | if (!response.ok) { 200 | throw new Error(await response.text()); 201 | } 202 | 203 | return await response.json(); 204 | } 205 | catch (e) { 206 | console.log("Sending request to trilium failed", e); 207 | 208 | toast('Your request failed because we could not contact Trilium instance. Please make sure Trilium is running and is accessible.'); 209 | 210 | return null; 211 | } 212 | } 213 | 214 | localNowDateTime() { 215 | const date = new Date(); 216 | const off = date.getTimezoneOffset(); 217 | const absoff = Math.abs(off); 218 | return (new Date(date.getTime() - off * 60 * 1000).toISOString().substr(0,23).replace("T", " ") + 219 | (off > 0 ? '-' : '+') + 220 | (absoff / 60).toFixed(0).padStart(2,'0') + ':' + 221 | (absoff % 60).toString().padStart(2,'0')); 222 | } 223 | } 224 | 225 | window.triliumServerFacade = new TriliumServerFacade(); 226 | -------------------------------------------------------------------------------- /lib/toast.js: -------------------------------------------------------------------------------- 1 | /*********************************************** 2 | 3 | "toast.js" 4 | 5 | Created by Michael Cheng on 05/31/2015 22:34 6 | http://michaelcheng.us/ 7 | michael@michaelcheng.us 8 | --All Rights Reserved-- 9 | 10 | ***********************************************/ 11 | 12 | 'use strict'; 13 | 14 | /** 15 | * The Toast animation speed; how long the Toast takes to move to and from the screen 16 | * @type {Number} 17 | */ 18 | const TOAST_ANIMATION_SPEED = 400; 19 | 20 | const Transitions = { 21 | SHOW: { 22 | '-webkit-transition': 'opacity ' + TOAST_ANIMATION_SPEED + 'ms, -webkit-transform ' + TOAST_ANIMATION_SPEED + 'ms', 23 | 'transition': 'opacity ' + TOAST_ANIMATION_SPEED + 'ms, transform ' + TOAST_ANIMATION_SPEED + 'ms', 24 | 'opacity': '1', 25 | '-webkit-transform': 'translateY(-100%) translateZ(0)', 26 | 'transform': 'translateY(-100%) translateZ(0)' 27 | }, 28 | 29 | HIDE: { 30 | 'opacity': '0', 31 | '-webkit-transform': 'translateY(150%) translateZ(0)', 32 | 'transform': 'translateY(150%) translateZ(0)' 33 | } 34 | }; 35 | 36 | /** 37 | * The main Toast object 38 | * @param {String} text The text to put inside the Toast 39 | * @param {Object} options Optional; the Toast options. See Toast.prototype.DEFAULT_SETTINGS for more information 40 | * @param {Object} transitions Optional; the Transitions object. This should not be used unless you know what you're doing 41 | */ 42 | function Toast(text, options, transitions) { 43 | if(getToastStage() !== null) { 44 | // If there is already a Toast being shown, put this Toast in the queue to show later 45 | Toast.prototype.toastQueue.push({ 46 | text: text, 47 | options: options, 48 | transitions: transitions 49 | }); 50 | } else { 51 | Toast.prototype.Transitions = transitions || Transitions; 52 | var _options = options || {}; 53 | _options = Toast.prototype.mergeOptions(Toast.prototype.DEFAULT_SETTINGS, _options); 54 | 55 | Toast.prototype.show(text, _options); 56 | 57 | _options = null; 58 | } 59 | } 60 | 61 | 62 | /** 63 | * The toastStage. This is the HTML element in which the toast resides 64 | * Getter and setter methods are available privately 65 | * @type {Element} 66 | */ 67 | var _toastStage = null; 68 | function getToastStage() { 69 | return _toastStage; 70 | } 71 | function setToastStage(toastStage) { 72 | _toastStage = toastStage; 73 | } 74 | 75 | 76 | 77 | 78 | // define some Toast constants 79 | 80 | /** 81 | * The default Toast settings 82 | * @type {Object} 83 | */ 84 | Toast.prototype.DEFAULT_SETTINGS = { 85 | style: { 86 | main: { 87 | 'background': 'rgba(0, 0, 0, .8)', 88 | 'box-shadow': '0 0 10px rgba(0, 0, 0, .8)', 89 | 90 | 'border-radius': '3px', 91 | 92 | 'z-index': '99999', 93 | 94 | 'color': 'rgba(255, 255, 255, .9)', 95 | 96 | 'padding': '10px 15px', 97 | 'max-width': '60%', 98 | 'width': '100%', 99 | 'word-break': 'keep-all', 100 | 'margin': '0 auto', 101 | 'text-align': 'center', 102 | 103 | 'position': 'fixed', 104 | 'left': '0', 105 | 'right': '0', 106 | 'bottom': '0', 107 | 108 | '-webkit-transform': 'translateY(150%) translateZ(0)', 109 | 'transform': 'translateY(150%) translateZ(0)', 110 | '-webkit-filter': 'blur(0)', 111 | 'opacity': '0' 112 | } 113 | }, 114 | 115 | settings: { 116 | duration: 4000 117 | } 118 | }; 119 | 120 | Toast.prototype.Transitions = {}; 121 | 122 | 123 | /** 124 | * The queue of Toasts waiting to be shown 125 | * @type {Array} 126 | */ 127 | Toast.prototype.toastQueue = []; 128 | 129 | 130 | /** 131 | * The Timeout object for animations. 132 | * This should be shared among the Toasts, because timeouts may be cancelled e.g. on explicit call of hide() 133 | * @type {Object} 134 | */ 135 | Toast.prototype.timeout = null; 136 | 137 | 138 | /** 139 | * Merge the DEFAULT_SETTINGS with the user defined options if specified 140 | * @param {Object} options The user defined options 141 | */ 142 | Toast.prototype.mergeOptions = function(initialOptions, customOptions) { 143 | var merged = customOptions; 144 | for(var prop in initialOptions) { 145 | if(merged.hasOwnProperty(prop)) { 146 | if(initialOptions[prop] !== null && initialOptions[prop].constructor === Object) { 147 | merged[prop] = Toast.prototype.mergeOptions(initialOptions[prop], merged[prop]); 148 | } 149 | } else { 150 | merged[prop] = initialOptions[prop]; 151 | } 152 | } 153 | return merged; 154 | }; 155 | 156 | 157 | /** 158 | * Generate the Toast with the specified text. 159 | * @param {String|Object} text The text to show inside the Toast, can be an HTML element or plain text 160 | * @param {Object} style The style to set for the Toast 161 | */ 162 | Toast.prototype.generate = function(text, style) { 163 | var toastStage = document.createElement('div'); 164 | 165 | 166 | /** 167 | * If the text is a String, create a textNode for appending 168 | */ 169 | if(typeof text === 'string') { 170 | text = document.createTextNode(text); 171 | } 172 | toastStage.appendChild(text); 173 | 174 | 175 | setToastStage(toastStage); 176 | toastStage = null; 177 | 178 | Toast.prototype.stylize(getToastStage(), style); 179 | }; 180 | 181 | /** 182 | * Stylize the Toast. 183 | * @param {Element} element The HTML element to stylize 184 | * @param {Object} styles An object containing the style to apply 185 | * @return Returns nothing 186 | */ 187 | Toast.prototype.stylize = function(element, styles) { 188 | Object.keys(styles).forEach(function(style) { 189 | element.style[style] = styles[style]; 190 | }); 191 | }; 192 | 193 | 194 | /** 195 | * Show the Toast 196 | * @param {String} text The text to show inside the Toast 197 | * @param {Object} options The object containing the options for the Toast 198 | */ 199 | Toast.prototype.show = function(text, options) { 200 | this.generate(text, options.style.main); 201 | 202 | var toastStage = getToastStage(); 203 | document.body.insertBefore(toastStage, document.body.firstChild); 204 | 205 | 206 | 207 | // This is a hack to get animations started. Apparently without explicitly redrawing, it'll just attach the class and no animations would be done 208 | toastStage.offsetHeight; 209 | 210 | 211 | Toast.prototype.stylize(toastStage, Toast.prototype.Transitions.SHOW); 212 | 213 | 214 | toastStage = null; 215 | 216 | 217 | // Hide the Toast after the specified time 218 | clearTimeout(Toast.prototype.timeout); 219 | Toast.prototype.timeout = setTimeout(Toast.prototype.hide, options.settings.duration); 220 | }; 221 | 222 | 223 | /** 224 | * Hide the Toast that's currently shown 225 | */ 226 | Toast.prototype.hide = function() { 227 | var toastStage = getToastStage(); 228 | Toast.prototype.stylize(toastStage, Toast.prototype.Transitions.HIDE); 229 | 230 | // Destroy the Toast element after animations end 231 | clearTimeout(Toast.prototype.timeout); 232 | toastStage.addEventListener('transitionend', Toast.prototype.animationListener); 233 | toastStage = null; 234 | }; 235 | 236 | Toast.prototype.animationListener = function() { 237 | getToastStage().removeEventListener('transitionend', Toast.prototype.animationListener); 238 | Toast.prototype.destroy.call(this); 239 | }; 240 | 241 | 242 | /** 243 | * Clean up after the Toast slides away. Namely, removing the Toast from the DOM. After the Toast is cleaned up, display the next Toast in the queue if any exists 244 | */ 245 | Toast.prototype.destroy = function() { 246 | var toastStage = getToastStage(); 247 | document.body.removeChild(toastStage); 248 | 249 | toastStage = null; 250 | setToastStage(null); 251 | 252 | 253 | if(Toast.prototype.toastQueue.length > 0) { 254 | // Show the rest of the Toasts in the queue if they exist 255 | 256 | var toast = Toast.prototype.toastQueue.shift(); 257 | Toast(toast.text, toast.options, toast.transitions); 258 | 259 | // clean up 260 | toast = null; 261 | } 262 | }; 263 | 264 | window.showToast = Toast; 265 | 266 | "END OF FILE"; // to avoid "result is non-structured-clonable data" -------------------------------------------------------------------------------- /content.js: -------------------------------------------------------------------------------- 1 | function absoluteUrl(url) { 2 | if (!url) { 3 | return url; 4 | } 5 | 6 | const protocol = url.toLowerCase().split(':')[0]; 7 | if (['http', 'https', 'file'].indexOf(protocol) >= 0) { 8 | return url; 9 | } 10 | 11 | if (url.indexOf('//') === 0) { 12 | return location.protocol + url; 13 | } else if (url[0] === '/') { 14 | return location.protocol + '//' + location.host + url; 15 | } else { 16 | return getBaseUrl() + '/' + url; 17 | } 18 | } 19 | 20 | function pageTitle() { 21 | const titleElements = document.getElementsByTagName("title"); 22 | 23 | return titleElements.length ? titleElements[0].text.trim() : document.title.trim(); 24 | } 25 | 26 | function getReadableDocument() { 27 | // Readability directly change the passed document, so clone to preserve the original web page. 28 | const documentCopy = document.cloneNode(true); 29 | const readability = new Readability(documentCopy, { 30 | serializer: el => el // so that .content is returned as DOM element instead of HTML 31 | }); 32 | 33 | const article = readability.parse(); 34 | 35 | if (!article) { 36 | throw new Error('Could not parse HTML document with Readability'); 37 | } 38 | 39 | return { 40 | title: article.title, 41 | body: article.content, 42 | } 43 | } 44 | 45 | function getDocumentDates() { 46 | var dates = { 47 | publishedDate: null, 48 | modifiedDate: null, 49 | }; 50 | 51 | const articlePublishedTime = document.querySelector("meta[property='article:published_time']"); 52 | if (articlePublishedTime && articlePublishedTime.getAttribute('content')) { 53 | dates.publishedDate = new Date(articlePublishedTime.getAttribute('content')); 54 | } 55 | 56 | const articleModifiedTime = document.querySelector("meta[property='article:modified_time']"); 57 | if (articleModifiedTime && articleModifiedTime.getAttribute('content')) { 58 | dates.modifiedDate = new Date(articleModifiedTime.getAttribute('content')); 59 | } 60 | 61 | // TODO: if we didn't get dates from meta, then try to get them from JSON-LD 62 | 63 | return dates; 64 | } 65 | 66 | function getRectangleArea() { 67 | return new Promise((resolve, reject) => { 68 | const overlay = document.createElement('div'); 69 | overlay.style.opacity = '0.6'; 70 | overlay.style.background = 'black'; 71 | overlay.style.width = '100%'; 72 | overlay.style.height = '100%'; 73 | overlay.style.zIndex = 99999999; 74 | overlay.style.top = 0; 75 | overlay.style.left = 0; 76 | overlay.style.position = 'fixed'; 77 | 78 | document.body.appendChild(overlay); 79 | 80 | const messageComp = document.createElement('div'); 81 | 82 | const messageCompWidth = 300; 83 | messageComp.setAttribute("tabindex", "0"); // so that it can be focused 84 | messageComp.style.position = 'fixed'; 85 | messageComp.style.opacity = '0.95'; 86 | messageComp.style.fontSize = '14px'; 87 | messageComp.style.width = messageCompWidth + 'px'; 88 | messageComp.style.maxWidth = messageCompWidth + 'px'; 89 | messageComp.style.border = '1px solid black'; 90 | messageComp.style.background = 'white'; 91 | messageComp.style.color = 'black'; 92 | messageComp.style.top = '10px'; 93 | messageComp.style.textAlign = 'center'; 94 | messageComp.style.padding = '10px'; 95 | messageComp.style.left = Math.round(document.body.clientWidth / 2 - messageCompWidth / 2) + 'px'; 96 | messageComp.style.zIndex = overlay.style.zIndex + 1; 97 | 98 | messageComp.textContent = 'Drag and release to capture a screenshot'; 99 | 100 | document.body.appendChild(messageComp); 101 | 102 | const selection = document.createElement('div'); 103 | selection.style.opacity = '0.5'; 104 | selection.style.border = '1px solid red'; 105 | selection.style.background = 'white'; 106 | selection.style.border = '2px solid black'; 107 | selection.style.zIndex = overlay.style.zIndex - 1; 108 | selection.style.top = 0; 109 | selection.style.left = 0; 110 | selection.style.position = 'fixed'; 111 | 112 | document.body.appendChild(selection); 113 | 114 | messageComp.focus(); // we listen on keypresses on this element to cancel on escape 115 | 116 | let isDragging = false; 117 | let draggingStartPos = null; 118 | let selectionArea = {}; 119 | 120 | function updateSelection() { 121 | selection.style.left = selectionArea.x + 'px'; 122 | selection.style.top = selectionArea.y + 'px'; 123 | selection.style.width = selectionArea.width + 'px'; 124 | selection.style.height = selectionArea.height + 'px'; 125 | } 126 | 127 | function setSelectionSizeFromMouse(event) { 128 | if (event.clientX < draggingStartPos.x) { 129 | selectionArea.x = event.clientX; 130 | } 131 | 132 | if (event.clientY < draggingStartPos.y) { 133 | selectionArea.y = event.clientY; 134 | } 135 | 136 | selectionArea.width = Math.max(1, Math.abs(event.clientX - draggingStartPos.x)); 137 | selectionArea.height = Math.max(1, Math.abs(event.clientY - draggingStartPos.y)); 138 | updateSelection(); 139 | } 140 | 141 | function selection_mouseDown(event) { 142 | selectionArea = {x: event.clientX, y: event.clientY, width: 0, height: 0}; 143 | draggingStartPos = {x: event.clientX, y: event.clientY}; 144 | isDragging = true; 145 | updateSelection(); 146 | } 147 | 148 | function selection_mouseMove(event) { 149 | if (!isDragging) return; 150 | setSelectionSizeFromMouse(event); 151 | } 152 | 153 | function removeOverlay() { 154 | isDragging = false; 155 | 156 | overlay.removeEventListener('mousedown', selection_mouseDown); 157 | overlay.removeEventListener('mousemove', selection_mouseMove); 158 | overlay.removeEventListener('mouseup', selection_mouseUp); 159 | 160 | document.body.removeChild(overlay); 161 | document.body.removeChild(selection); 162 | document.body.removeChild(messageComp); 163 | } 164 | 165 | function selection_mouseUp(event) { 166 | setSelectionSizeFromMouse(event); 167 | 168 | removeOverlay(); 169 | 170 | console.info('selectionArea:', selectionArea); 171 | 172 | if (!selectionArea || !selectionArea.width || !selectionArea.height) { 173 | return; 174 | } 175 | 176 | // Need to wait a bit before taking the screenshot to make sure 177 | // the overlays have been removed and don't appear in the 178 | // screenshot. 10ms is not enough. 179 | setTimeout(() => resolve(selectionArea), 100); 180 | } 181 | 182 | function cancel(event) { 183 | if (event.key === "Escape") { 184 | removeOverlay(); 185 | } 186 | } 187 | 188 | overlay.addEventListener('mousedown', selection_mouseDown); 189 | overlay.addEventListener('mousemove', selection_mouseMove); 190 | overlay.addEventListener('mouseup', selection_mouseUp); 191 | overlay.addEventListener('mouseup', selection_mouseUp); 192 | messageComp.addEventListener('keydown', cancel); 193 | }); 194 | } 195 | 196 | function makeLinksAbsolute(container) { 197 | for (const link of container.getElementsByTagName('a')) { 198 | if (link.href) { 199 | link.href = absoluteUrl(link.href); 200 | } 201 | } 202 | } 203 | 204 | function getImages(container) { 205 | const images = []; 206 | 207 | for (const img of container.getElementsByTagName('img')) { 208 | if (!img.src) { 209 | continue; 210 | } 211 | 212 | const existingImage = images.find(image => image.src === img.src); 213 | 214 | if (existingImage) { 215 | img.src = existingImage.imageId; 216 | } 217 | else { 218 | const imageId = randomString(20); 219 | 220 | images.push({ 221 | imageId: imageId, 222 | src: img.src 223 | }); 224 | 225 | img.src = imageId; 226 | } 227 | } 228 | 229 | return images; 230 | } 231 | 232 | function createLink(clickAction, text, color = "lightskyblue") { 233 | const link = document.createElement('a'); 234 | link.href = "javascript:"; 235 | link.style.color = color; 236 | link.appendChild(document.createTextNode(text)); 237 | link.addEventListener("click", () => { 238 | browser.runtime.sendMessage(null, clickAction) 239 | }); 240 | 241 | return link 242 | } 243 | 244 | async function prepareMessageResponse(message) { 245 | console.info('Message: ' + message.name); 246 | 247 | if (message.name === "toast") { 248 | let messageText; 249 | 250 | if (message.noteId) { 251 | messageText = document.createElement('p'); 252 | messageText.setAttribute("style", "padding: 0; margin: 0; font-size: larger;") 253 | messageText.appendChild(document.createTextNode(message.message + " ")); 254 | messageText.appendChild(createLink( 255 | {name: 'openNoteInTrilium', noteId: message.noteId}, 256 | "Open in Trilium." 257 | )); 258 | 259 | // only after saving tabs 260 | if (message.tabIds) { 261 | messageText.appendChild(document.createElement("br")); 262 | messageText.appendChild(createLink( 263 | {name: 'closeTabs', tabIds: message.tabIds}, 264 | "Close saved tabs.", 265 | "tomato" 266 | )); 267 | } 268 | } 269 | else { 270 | messageText = message.message; 271 | } 272 | 273 | await requireLib('/lib/toast.js'); 274 | 275 | showToast(messageText, { 276 | settings: { 277 | duration: 7000 278 | } 279 | }); 280 | } 281 | else if (message.name === "trilium-save-selection") { 282 | const container = document.createElement('div'); 283 | 284 | const selection = window.getSelection(); 285 | 286 | for (let i = 0; i < selection.rangeCount; i++) { 287 | const range = selection.getRangeAt(i); 288 | 289 | container.appendChild(range.cloneContents()); 290 | } 291 | 292 | makeLinksAbsolute(container); 293 | 294 | const images = getImages(container); 295 | 296 | return { 297 | title: pageTitle(), 298 | content: container.innerHTML, 299 | images: images, 300 | pageUrl: getPageLocationOrigin() + location.pathname + location.search + location.hash 301 | }; 302 | 303 | } 304 | else if (message.name === 'trilium-get-rectangle-for-screenshot') { 305 | return getRectangleArea(); 306 | } 307 | else if (message.name === "trilium-save-page") { 308 | await requireLib("/lib/JSDOMParser.js"); 309 | await requireLib("/lib/Readability.js"); 310 | await requireLib("/lib/Readability-readerable.js"); 311 | 312 | const {title, body} = getReadableDocument(); 313 | 314 | makeLinksAbsolute(body); 315 | 316 | const images = getImages(body); 317 | 318 | var labels = {}; 319 | const dates = getDocumentDates(); 320 | if (dates.publishedDate) { 321 | labels['publishedDate'] = dates.publishedDate.toISOString().substring(0, 10); 322 | } 323 | if (dates.modifiedDate) { 324 | labels['modifiedDate'] = dates.publishedDate.toISOString().substring(0, 10); 325 | } 326 | 327 | return { 328 | title: title, 329 | content: body.innerHTML, 330 | images: images, 331 | pageUrl: getPageLocationOrigin() + location.pathname + location.search, 332 | clipType: 'page', 333 | labels: labels 334 | }; 335 | } 336 | else { 337 | throw new Error('Unknown command: ' + JSON.stringify(message)); 338 | } 339 | } 340 | 341 | browser.runtime.onMessage.addListener(prepareMessageResponse); 342 | 343 | const loadedLibs = []; 344 | 345 | async function requireLib(libPath) { 346 | if (!loadedLibs.includes(libPath)) { 347 | loadedLibs.push(libPath); 348 | 349 | await browser.runtime.sendMessage({name: 'load-script', file: libPath}); 350 | } 351 | } 352 | -------------------------------------------------------------------------------- /background.js: -------------------------------------------------------------------------------- 1 | // Keyboard shortcuts 2 | chrome.commands.onCommand.addListener(async function (command) { 3 | if (command == "saveSelection") { 4 | await saveSelection(); 5 | } else if (command == "saveWholePage") { 6 | await saveWholePage(); 7 | } else if (command == "saveTabs") { 8 | await saveTabs(); 9 | } else if (command == "saveCroppedScreenshot") { 10 | const activeTab = await getActiveTab(); 11 | 12 | await saveCroppedScreenshot(activeTab.url); 13 | } else { 14 | console.log("Unrecognized command", command); 15 | } 16 | }); 17 | 18 | function cropImage(newArea, dataUrl) { 19 | return new Promise((resolve, reject) => { 20 | const img = new Image(); 21 | 22 | img.onload = function () { 23 | const canvas = document.createElement('canvas'); 24 | canvas.width = newArea.width; 25 | canvas.height = newArea.height; 26 | 27 | const ctx = canvas.getContext('2d'); 28 | 29 | ctx.drawImage(img, newArea.x, newArea.y, newArea.width, newArea.height, 0, 0, newArea.width, newArea.height); 30 | 31 | resolve(canvas.toDataURL()); 32 | }; 33 | 34 | img.src = dataUrl; 35 | }); 36 | } 37 | 38 | async function takeCroppedScreenshot(cropRect) { 39 | const activeTab = await getActiveTab(); 40 | const zoom = await browser.tabs.getZoom(activeTab.id) * window.devicePixelRatio; 41 | 42 | const newArea = Object.assign({}, cropRect); 43 | newArea.x *= zoom; 44 | newArea.y *= zoom; 45 | newArea.width *= zoom; 46 | newArea.height *= zoom; 47 | 48 | const dataUrl = await browser.tabs.captureVisibleTab(null, { format: 'png' }); 49 | 50 | return await cropImage(newArea, dataUrl); 51 | } 52 | 53 | async function takeWholeScreenshot() { 54 | // this saves only visible portion of the page 55 | // workaround to save the whole page is to scroll & stitch 56 | // example in https://github.com/mrcoles/full-page-screen-capture-chrome-extension 57 | // see page.js and popup.js 58 | return await browser.tabs.captureVisibleTab(null, { format: 'png' }); 59 | } 60 | 61 | browser.runtime.onInstalled.addListener(() => { 62 | if (isDevEnv()) { 63 | browser.browserAction.setIcon({ 64 | path: 'icons/32-dev.png', 65 | }); 66 | } 67 | }); 68 | 69 | browser.contextMenus.create({ 70 | id: "trilium-save-selection", 71 | title: "Save selection to Trilium", 72 | contexts: ["selection"] 73 | }); 74 | 75 | browser.contextMenus.create({ 76 | id: "trilium-save-cropped-screenshot", 77 | title: "Clip screenshot to Trilium", 78 | contexts: ["page"] 79 | }); 80 | 81 | browser.contextMenus.create({ 82 | id: "trilium-save-cropped-screenshot", 83 | title: "Crop screen shot to Trilium", 84 | contexts: ["page"] 85 | }); 86 | 87 | browser.contextMenus.create({ 88 | id: "trilium-save-whole-screenshot", 89 | title: "Save whole screen shot to Trilium", 90 | contexts: ["page"] 91 | }); 92 | 93 | browser.contextMenus.create({ 94 | id: "trilium-save-page", 95 | title: "Save whole page to Trilium", 96 | contexts: ["page"] 97 | }); 98 | 99 | browser.contextMenus.create({ 100 | id: "trilium-save-link", 101 | title: "Save link to Trilium", 102 | contexts: ["link"] 103 | }); 104 | 105 | browser.contextMenus.create({ 106 | id: "trilium-save-image", 107 | title: "Save image to Trilium", 108 | contexts: ["image"] 109 | }); 110 | 111 | async function getActiveTab() { 112 | const tabs = await browser.tabs.query({ 113 | active: true, 114 | currentWindow: true 115 | }); 116 | 117 | return tabs[0]; 118 | } 119 | 120 | async function getWindowTabs() { 121 | const tabs = await browser.tabs.query({ 122 | currentWindow: true 123 | }); 124 | 125 | return tabs; 126 | } 127 | 128 | async function sendMessageToActiveTab(message) { 129 | const activeTab = await getActiveTab(); 130 | 131 | if (!activeTab) { 132 | throw new Error("No active tab."); 133 | } 134 | 135 | try { 136 | return await browser.tabs.sendMessage(activeTab.id, message); 137 | } 138 | catch (e) { 139 | throw e; 140 | } 141 | } 142 | 143 | function toast(message, noteId = null, tabIds = null) { 144 | sendMessageToActiveTab({ 145 | name: 'toast', 146 | message: message, 147 | noteId: noteId, 148 | tabIds: tabIds 149 | }); 150 | } 151 | 152 | function blob2base64(blob) { 153 | return new Promise(resolve => { 154 | const reader = new FileReader(); 155 | reader.onloadend = function() { 156 | resolve(reader.result); 157 | }; 158 | reader.readAsDataURL(blob); 159 | }); 160 | } 161 | 162 | async function fetchImage(url) { 163 | const resp = await fetch(url); 164 | const blob = await resp.blob(); 165 | 166 | return await blob2base64(blob); 167 | } 168 | 169 | async function postProcessImage(image) { 170 | if (image.src.startsWith("data:image/")) { 171 | image.dataUrl = image.src; 172 | image.src = "inline." + image.src.substr(11, 3); // this should extract file type - png/jpg 173 | } 174 | else { 175 | try { 176 | image.dataUrl = await fetchImage(image.src, image); 177 | } 178 | catch (e) { 179 | console.log(`Cannot fetch image from ${image.src}`); 180 | } 181 | } 182 | } 183 | 184 | async function postProcessImages(resp) { 185 | if (resp.images) { 186 | for (const image of resp.images) { 187 | await postProcessImage(image); 188 | } 189 | } 190 | } 191 | 192 | async function saveSelection() { 193 | const payload = await sendMessageToActiveTab({name: 'trilium-save-selection'}); 194 | 195 | await postProcessImages(payload); 196 | 197 | const resp = await triliumServerFacade.callService('POST', 'clippings', payload); 198 | 199 | if (!resp) { 200 | return; 201 | } 202 | 203 | toast("Selection has been saved to Trilium.", resp.noteId); 204 | } 205 | 206 | async function getImagePayloadFromSrc(src, pageUrl) { 207 | const image = { 208 | imageId: randomString(20), 209 | src: src 210 | }; 211 | 212 | await postProcessImage(image); 213 | 214 | const activeTab = await getActiveTab(); 215 | 216 | return { 217 | title: activeTab.title, 218 | content: ``, 219 | images: [image], 220 | pageUrl: pageUrl 221 | }; 222 | } 223 | 224 | async function saveCroppedScreenshot(pageUrl) { 225 | const cropRect = await sendMessageToActiveTab({name: 'trilium-get-rectangle-for-screenshot'}); 226 | 227 | const src = await takeCroppedScreenshot(cropRect); 228 | 229 | const payload = await getImagePayloadFromSrc(src, pageUrl); 230 | 231 | const resp = await triliumServerFacade.callService("POST", "clippings", payload); 232 | 233 | if (!resp) { 234 | return; 235 | } 236 | 237 | toast("Screenshot has been saved to Trilium.", resp.noteId); 238 | } 239 | 240 | async function saveWholeScreenshot(pageUrl) { 241 | const src = await takeWholeScreenshot(); 242 | 243 | const payload = await getImagePayloadFromSrc(src, pageUrl); 244 | 245 | const resp = await triliumServerFacade.callService("POST", "clippings", payload); 246 | 247 | if (!resp) { 248 | return; 249 | } 250 | 251 | toast("Screenshot has been saved to Trilium.", resp.noteId); 252 | } 253 | 254 | async function saveImage(srcUrl, pageUrl) { 255 | const payload = await getImagePayloadFromSrc(srcUrl, pageUrl); 256 | 257 | const resp = await triliumServerFacade.callService("POST", "clippings", payload); 258 | 259 | if (!resp) { 260 | return; 261 | } 262 | 263 | toast("Image has been saved to Trilium.", resp.noteId); 264 | } 265 | 266 | async function saveWholePage() { 267 | const payload = await sendMessageToActiveTab({name: 'trilium-save-page'}); 268 | 269 | await postProcessImages(payload); 270 | 271 | const resp = await triliumServerFacade.callService('POST', 'notes', payload); 272 | 273 | if (!resp) { 274 | return; 275 | } 276 | 277 | toast("Page has been saved to Trilium.", resp.noteId); 278 | } 279 | 280 | async function saveLinkWithNote(title, content) { 281 | const activeTab = await getActiveTab(); 282 | 283 | if (!title.trim()) { 284 | title = activeTab.title; 285 | } 286 | 287 | const resp = await triliumServerFacade.callService('POST', 'notes', { 288 | title: title, 289 | content: content, 290 | clipType: 'note', 291 | pageUrl: activeTab.url 292 | }); 293 | 294 | if (!resp) { 295 | return false; 296 | } 297 | 298 | toast("Link with note has been saved to Trilium.", resp.noteId); 299 | 300 | return true; 301 | } 302 | 303 | async function getTabsPayload(tabs) { 304 | let content = '
    '; 305 | tabs.forEach(tab => { 306 | content += `
  • ${tab.title}
  • ` 307 | }); 308 | content += '
'; 309 | 310 | const domainsCount = tabs.map(tab => tab.url) 311 | .reduce((acc, url) => { 312 | const hostname = new URL(url).hostname 313 | return acc.set(hostname, (acc.get(hostname) || 0) + 1) 314 | }, new Map()); 315 | 316 | let topDomains = [...domainsCount] 317 | .sort((a, b) => {return b[1]-a[1]}) 318 | .slice(0,3) 319 | .map(domain=>domain[0]) 320 | .join(', ') 321 | 322 | if (tabs.length > 3) { topDomains += '...' } 323 | 324 | return { 325 | title: `${tabs.length} browser tabs: ${topDomains}`, 326 | content: content, 327 | clipType: 'tabs' 328 | }; 329 | } 330 | 331 | async function saveTabs() { 332 | const tabs = await getWindowTabs(); 333 | 334 | const payload = await getTabsPayload(tabs); 335 | 336 | const resp = await triliumServerFacade.callService('POST', 'notes', payload); 337 | 338 | if (!resp) { 339 | return; 340 | } 341 | 342 | const tabIds = tabs.map(tab=>{return tab.id}); 343 | 344 | toast(`${tabs.length} links have been saved to Trilium.`, resp.noteId, tabIds); 345 | } 346 | 347 | browser.contextMenus.onClicked.addListener(async function(info, tab) { 348 | if (info.menuItemId === 'trilium-save-selection') { 349 | await saveSelection(); 350 | } 351 | else if (info.menuItemId === 'trilium-save-cropped-screenshot') { 352 | await saveCroppedScreenshot(info.pageUrl); 353 | } 354 | else if (info.menuItemId === 'trilium-save-whole-screenshot') { 355 | await saveWholeScreenshot(info.pageUrl); 356 | } 357 | else if (info.menuItemId === 'trilium-save-image') { 358 | await saveImage(info.srcUrl, info.pageUrl); 359 | } 360 | else if (info.menuItemId === 'trilium-save-link') { 361 | const link = document.createElement("a"); 362 | link.href = info.linkUrl; 363 | // linkText might be available only in firefox 364 | link.appendChild(document.createTextNode(info.linkText || info.linkUrl)); 365 | 366 | const activeTab = await getActiveTab(); 367 | 368 | const resp = await triliumServerFacade.callService('POST', 'clippings', { 369 | title: activeTab.title, 370 | content: link.outerHTML, 371 | pageUrl: info.pageUrl 372 | }); 373 | 374 | if (!resp) { 375 | return; 376 | } 377 | 378 | toast("Link has been saved to Trilium.", resp.noteId); 379 | } 380 | else if (info.menuItemId === 'trilium-save-page') { 381 | await saveWholePage(); 382 | } 383 | else { 384 | console.log("Unrecognized menuItemId", info.menuItemId); 385 | } 386 | }); 387 | 388 | browser.runtime.onMessage.addListener(async request => { 389 | console.log("Received", request); 390 | 391 | if (request.name === 'openNoteInTrilium') { 392 | const resp = await triliumServerFacade.callService('POST', 'open/' + request.noteId); 393 | 394 | if (!resp) { 395 | return; 396 | } 397 | 398 | // desktop app is not available so we need to open in browser 399 | if (resp.result === 'open-in-browser') { 400 | const {triliumServerUrl} = await browser.storage.sync.get("triliumServerUrl"); 401 | 402 | if (triliumServerUrl) { 403 | const noteUrl = triliumServerUrl + '/#' + request.noteId; 404 | 405 | console.log("Opening new tab in browser", noteUrl); 406 | 407 | browser.tabs.create({ 408 | url: noteUrl 409 | }); 410 | } 411 | else { 412 | console.error("triliumServerUrl not found in local storage."); 413 | } 414 | } 415 | } 416 | else if (request.name === 'closeTabs') { 417 | return await browser.tabs.remove(request.tabIds) 418 | } 419 | else if (request.name === 'load-script') { 420 | return await browser.tabs.executeScript({file: request.file}); 421 | } 422 | else if (request.name === 'save-cropped-screenshot') { 423 | const activeTab = await getActiveTab(); 424 | 425 | return await saveCroppedScreenshot(activeTab.url); 426 | } 427 | else if (request.name === 'save-whole-screenshot') { 428 | const activeTab = await getActiveTab(); 429 | 430 | return await saveWholeScreenshot(activeTab.url); 431 | } 432 | else if (request.name === 'save-whole-page') { 433 | return await saveWholePage(); 434 | } 435 | else if (request.name === 'save-link-with-note') { 436 | return await saveLinkWithNote(request.title, request.content); 437 | } 438 | else if (request.name === 'save-tabs') { 439 | return await saveTabs(); 440 | } 441 | else if (request.name === 'trigger-trilium-search') { 442 | triliumServerFacade.triggerSearchForTrilium(); 443 | } 444 | else if (request.name === 'send-trilium-search-status') { 445 | triliumServerFacade.sendTriliumSearchStatusToPopup(); 446 | } 447 | else if (request.name === 'trigger-trilium-search-note-url') { 448 | const activeTab = await getActiveTab(); 449 | triliumServerFacade.triggerSearchNoteByUrl(activeTab.url); 450 | } 451 | }); 452 | -------------------------------------------------------------------------------- /lib/cash.min.js: -------------------------------------------------------------------------------- 1 | /* MIT https://github.com/kenwheeler/cash */ 2 | (function(){ 3 | 'use strict';var e={"class":"className",contenteditable:"contentEditable","for":"htmlFor",readonly:"readOnly",maxlength:"maxLength",tabindex:"tabIndex",colspan:"colSpan",rowspan:"rowSpan",usemap:"useMap"};function g(a,b){try{return a(b)}catch(c){return b}} 4 | var m=document,n=window,p=m.documentElement,r=m.createElement.bind(m),aa=r("div"),t=r("table"),ba=r("tbody"),ca=r("tr"),u=Array.isArray,v=Array.prototype,da=v.concat,w=v.filter,ea=v.indexOf,fa=v.map,ha=v.push,ia=v.slice,x=v.some,ja=v.splice,ka=/^#[\w-]*$/,la=/^\.[\w-]*$/,ma=/<.+>/,na=/^\w+$/;function y(a,b){return a&&(A(b)||B(b))?la.test(a)?b.getElementsByClassName(a.slice(1)):na.test(a)?b.getElementsByTagName(a):b.querySelectorAll(a):[]} 5 | var C=function(){function a(a,c){if(a){if(a instanceof C)return a;var b=a;if(D(a)){if(b=(c instanceof C?c[0]:c)||m,b=ka.test(a)?b.getElementById(a.slice(1)):ma.test(a)?oa(a):y(a,b),!b)return}else if(E(a))return this.ready(a);if(b.nodeType||b===n)b=[b];this.length=b.length;a=0;for(c=this.length;aarguments.length?this[0]&&this[0][a]:this.each(function(c,h){h[a]=b});for(var c in a)this.prop(c,a[c]);return this}};F.get=function(a){if(void 0===a)return ia.call(this);a=Number(a);return this[0>a?a+this.length:a]};F.eq=function(a){return G(this.get(a))}; 9 | F.first=function(){return this.eq(0)};F.last=function(){return this.eq(-1)};function L(a){return D(a)?function(b,c){return qa(c,a)}:E(a)?a:a instanceof C?function(b,c){return a.is(c)}:a?function(b,c){return c===a}:function(){return!1}}F.filter=function(a){var b=L(a);return G(w.call(this,function(a,d){return b.call(a,d,a)}))};function M(a,b){return b?a.filter(b):a}var sa=/\S+/g;function N(a){return D(a)?a.match(sa)||[]:[]}F.hasClass=function(a){return!!a&&x.call(this,function(b){return B(b)&&b.classList.contains(a)})}; 10 | F.removeAttr=function(a){var b=N(a);return this.each(function(a,d){B(d)&&I(b,function(a,b){d.removeAttribute(b)})})};F.attr=function(a,b){if(a){if(D(a)){if(2>arguments.length){if(!this[0]||!B(this[0]))return;var c=this[0].getAttribute(a);return null===c?void 0:c}return void 0===b?this:null===b?this.removeAttr(a):this.each(function(c,h){B(h)&&h.setAttribute(a,b)})}for(c in a)this.attr(c,a[c]);return this}}; 11 | F.toggleClass=function(a,b){var c=N(a),d=void 0!==b;return this.each(function(a,f){B(f)&&I(c,function(a,c){d?b?f.classList.add(c):f.classList.remove(c):f.classList.toggle(c)})})};F.addClass=function(a){return this.toggleClass(a,!0)};F.removeClass=function(a){return arguments.length?this.toggleClass(a,!1):this.attr("class","")}; 12 | function O(a,b,c,d){for(var h=[],f=E(b),k=d&&L(d),q=0,R=a.length;qarguments.length)return this[0]&&Q(this[0],a,c);if(!a)return this;b=xa(a,b,c);return this.each(function(d,f){B(f)&&(c?f.style.setProperty(a,b):f.style[a]=b)})}for(var d in a)this.css(d,a[d]);return this};var ya=/^\s+|\s+$/;function za(a,b){a=a.dataset[b]||a.dataset[H(b)];return ya.test(a)?a:g(JSON.parse,a)} 16 | F.data=function(a,b){if(!a){if(!this[0])return;var c={},d;for(d in this[0].dataset)c[d]=za(this[0],d);return c}if(D(a))return 2>arguments.length?this[0]&&za(this[0],a):void 0===b?this:this.each(function(c,d){c=b;c=g(JSON.stringify,c);d.dataset[H(a)]=c});for(d in a)this.data(d,a[d]);return this};function Aa(a,b){var c=a.documentElement;return Math.max(a.body["scroll"+b],c["scroll"+b],a.body["offset"+b],c["offset"+b],c["client"+b])} 17 | function Ba(a,b){return S(a,"border"+(b?"Left":"Top")+"Width")+S(a,"padding"+(b?"Left":"Top"))+S(a,"padding"+(b?"Right":"Bottom"))+S(a,"border"+(b?"Right":"Bottom")+"Width")} 18 | I([!0,!1],function(a,b){I(["Width","Height"],function(a,d){F[(b?"outer":"inner")+d]=function(c){if(this[0])return K(this[0])?b?this[0]["inner"+d]:this[0].document.documentElement["client"+d]:A(this[0])?Aa(this[0],d):this[0][(b?"offset":"client")+d]+(c&&b?S(this[0],"margin"+(a?"Top":"Left"))+S(this[0],"margin"+(a?"Bottom":"Right")):0)}})}); 19 | I(["Width","Height"],function(a,b){var c=b.toLowerCase();F[c]=function(d){if(!this[0])return void 0===d?void 0:this;if(!arguments.length)return K(this[0])?this[0].document.documentElement["client"+b]:A(this[0])?Aa(this[0],b):this[0].getBoundingClientRect()[c]-Ba(this[0],!a);var h=parseInt(d,10);return this.each(function(b,d){B(d)&&(b=Q(d,"boxSizing"),d.style[c]=xa(c,h+("border-box"===b?Ba(d,!a):0)))})}});var V={}; 20 | F.toggle=function(a){return this.each(function(b,c){if(B(c))if(void 0===a?"none"===Q(c,"display"):a){if(c.style.display=c.___cd||"","none"===Q(c,"display")){b=c.style;c=c.tagName;if(V[c])c=V[c];else{var d=r(c);m.body.insertBefore(d,null);var h=Q(d,"display");m.body.removeChild(d);c=V[c]="none"!==h?h:"block"}b.display=c}}else c.___cd=Q(c,"display"),c.style.display="none"})};F.hide=function(){return this.toggle(!1)};F.show=function(){return this.toggle(!0)}; 21 | function Ca(a,b){return!b||!x.call(b,function(b){return 0>a.indexOf(b)})}var W={focus:"focusin",blur:"focusout"},Da={mouseenter:"mouseover",mouseleave:"mouseout"},Ea=/^(mouse|pointer|contextmenu|drag|drop|click|dblclick)/i;function Fa(a,b,c,d,h){var f=a.___ce=a.___ce||{};f[b]=f[b]||[];f[b].push([c,d,h]);a.addEventListener(b,h)}function X(a){a=a.split(".");return[a[0],a.slice(1).sort()]} 22 | function Y(a,b,c,d,h){var f=a.___ce=a.___ce||{};if(b)f[b]&&(f[b]=f[b].filter(function(f){var k=f[0],R=f[1];f=f[2];if(h&&f.guid!==h.guid||!Ca(k,c)||d&&d!==R)return!0;a.removeEventListener(b,f)}));else for(b in f)Y(a,b,c,d,h)} 23 | F.off=function(a,b,c){var d=this;if(void 0===a)this.each(function(a,b){(B(b)||A(b)||K(b))&&Y(b)});else if(D(a))E(b)&&(c=b,b=""),I(N(a),function(a,h){a=X(Da[h]||W[h]||h);var f=a[0],k=a[1];d.each(function(a,d){(B(d)||A(d)||K(d))&&Y(d,f,k,b,c)})});else for(var h in a)this.off(h,a[h]);return this}; 24 | F.on=function(a,b,c,d,h){var f=this;if(!D(a)){for(var k in a)this.on(k,b,c,a[k],h);return this}D(b)||(void 0!==b&&null!==b&&(void 0!==c&&(d=c),c=b),b="");E(d)||(d=c,c=void 0);if(!d)return this;I(N(a),function(a,k){a=X(Da[k]||W[k]||k);var l=a[0],q=a[1];l&&f.each(function(a,f){if(B(f)||A(f)||K(f))a=function Ja(a){if(!a.namespace||Ca(q,a.namespace.split("."))){var k=f;if(b){for(var z=a.target;!qa(z,b);){if(z===f)return;z=z.parentNode;if(!z)return}k=z;a.___cd=!0}a.___cd&&Object.defineProperty(a,"currentTarget", 25 | {configurable:!0,get:function(){return k}});Object.defineProperty(a,"data",{configurable:!0,get:function(){return c}});z=d.call(k,a,a.___td);h&&Y(f,l,q,b,Ja);!1===z&&(a.preventDefault(),a.stopPropagation())}},a.guid=d.guid=d.guid||G.guid++,Fa(f,l,q,b,a)})});return this};F.one=function(a,b,c,d){return this.on(a,b,c,d,!0)};F.ready=function(a){function b(){return setTimeout(a,0,G)}"loading"!==m.readyState?b():m.addEventListener("DOMContentLoaded",b);return this}; 26 | F.trigger=function(a,b){if(D(a)){var c=X(a),d=c[0];c=c[1];if(!d)return this;var h=Ea.test(d)?"MouseEvents":"HTMLEvents";a=m.createEvent(h);a.initEvent(d,!0,!0);a.namespace=c.join(".")}a.___td=b;var f=a.type in W;return this.each(function(b,c){if(f&&E(c[a.type]))c[a.type]();else c.dispatchEvent(a)})};function Ga(a){return a.multiple&&a.options?O(w.call(a.options,function(a){return a.selected&&!a.disabled&&!a.parentNode.disabled}),"value"):a.value||""} 27 | var Ha=/%20/g,Ia=/\r?\n/g,Ka=/file|reset|submit|button|image/i,La=/radio|checkbox/i;F.serialize=function(){var a="";this.each(function(b,c){I(c.elements||[c],function(b,c){c.disabled||!c.name||"FIELDSET"===c.tagName||Ka.test(c.type)||La.test(c.type)&&!c.checked||(b=Ga(c),void 0!==b&&(b=u(b)?b:[b],I(b,function(b,d){b=a;d="&"+encodeURIComponent(c.name)+"="+encodeURIComponent(d.replace(Ia,"\r\n")).replace(Ha,"+");a=b+d})))})});return a.slice(1)}; 28 | F.val=function(a){return arguments.length?this.each(function(b,c){if((b=c.multiple&&c.options)||La.test(c.type)){var d=u(a)?fa.call(a,String):null===a?[]:[String(a)];b?I(c.options,function(a,b){b.selected=0<=d.indexOf(b.value)},!0):c.checked=0<=d.indexOf(c.value)}else c.value=void 0===a||null===a?"":a}):this[0]&&Ga(this[0])};F.clone=function(){return this.map(function(a,b){return b.cloneNode(!0)})};F.detach=function(a){M(this,a).each(function(a,c){c.parentNode&&c.parentNode.removeChild(c)});return this}; 29 | var Ma=/^\s*<(\w+)[^>]*>/,Na=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,Oa={"*":aa,tr:ba,td:ca,th:ca,thead:t,tbody:t,tfoot:t};function oa(a){if(!D(a))return[];if(Na.test(a))return[r(RegExp.$1)];var b=Ma.test(a)&&RegExp.$1;b=Oa[b]||Oa["*"];b.innerHTML=a;return G(b.childNodes).detach().get()}G.parseHTML=oa;F.empty=function(){return this.each(function(a,b){for(;b.firstChild;)b.removeChild(b.firstChild)})}; 30 | F.html=function(a){return arguments.length?void 0===a?this:this.each(function(b,c){B(c)&&(c.innerHTML=a)}):this[0]&&this[0].innerHTML};F.remove=function(a){M(this,a).detach().off();return this};F.text=function(a){return void 0===a?this[0]?this[0].textContent:"":this.each(function(b,c){B(c)&&(c.textContent=a)})};F.unwrap=function(){this.parent().each(function(a,b){"BODY"!==b.tagName&&(a=G(b),a.replaceWith(a.children()))});return this}; 31 | F.offset=function(){var a=this[0];if(a)return a=a.getBoundingClientRect(),{top:a.top+n.pageYOffset,left:a.left+n.pageXOffset}};F.offsetParent=function(){return this.map(function(a,b){for(a=b.offsetParent;a&&"static"===Q(a,"position");)a=a.offsetParent;return a||p})}; 32 | F.position=function(){var a=this[0];if(a){var b="fixed"===Q(a,"position"),c=b?a.getBoundingClientRect():this.offset();if(!b){var d=a.ownerDocument;for(b=a.offsetParent||d.documentElement;(b===d.body||b===d.documentElement)&&"static"===Q(b,"position");)b=b.parentNode;b!==a&&B(b)&&(d=G(b).offset(),c.top-=d.top+S(b,"borderTopWidth"),c.left-=d.left+S(b,"borderLeftWidth"))}return{top:c.top-S(a,"marginTop"),left:c.left-S(a,"marginLeft")}}}; 33 | F.children=function(a){return M(G(P(O(this,function(a){return a.children}))),a)};F.contents=function(){return G(P(O(this,function(a){return"IFRAME"===a.tagName?[a.contentDocument]:"TEMPLATE"===a.tagName?a.content.childNodes:a.childNodes})))};F.find=function(a){return G(P(O(this,function(b){return y(a,b)})))};var Pa=/^\s*\s*$/g,Qa=/^$|^module$|\/(java|ecma)script/i,Ra=["type","src","nonce","noModule"]; 34 | function Sa(a,b){a=G(a);a.filter("script").add(a.find("script")).each(function(a,d){if(Qa.test(d.type)&&p.contains(d)){var c=r("script");c.text=d.textContent.replace(Pa,"");I(Ra,function(a,b){d[b]&&(c[b]=d[b])});b.head.insertBefore(c,null);b.head.removeChild(c)}})} 35 | function Z(a,b,c,d,h,f,k,q){I(a,function(a,f){I(G(f),function(a,f){I(G(b),function(b,k){var l=c?k:f;b=c?a:b;k=c?f:k;l=b?l.cloneNode(!0):l;b=!b;h?k.insertBefore(l,d?k.firstChild:null):k.parentNode.insertBefore(l,d?k:k.nextSibling);b&&Sa(l,k.ownerDocument)},q)},k)},f);return b}F.after=function(){return Z(arguments,this,!1,!1,!1,!0,!0)};F.append=function(){return Z(arguments,this,!1,!1,!0)};F.appendTo=function(a){return Z(arguments,this,!0,!1,!0)};F.before=function(){return Z(arguments,this,!1,!0)}; 36 | F.insertAfter=function(a){return Z(arguments,this,!0,!1,!1,!1,!1,!0)};F.insertBefore=function(a){return Z(arguments,this,!0,!0)};F.prepend=function(){return Z(arguments,this,!1,!0,!0,!0,!0)};F.prependTo=function(a){return Z(arguments,this,!0,!0,!0,!1,!1,!0)};F.replaceWith=function(a){return this.before(a).remove()};F.replaceAll=function(a){G(a).replaceWith(this);return this};F.wrapAll=function(a){a=G(a);for(var b=a[0];b.children.length;)b=b.firstElementChild;this.first().before(a);return this.appendTo(b)}; 37 | F.wrap=function(a){return this.each(function(b,c){var d=G(a)[0];G(c).wrapAll(b?d.cloneNode(!0):d)})};F.wrapInner=function(a){return this.each(function(b,c){b=G(c);c=b.contents();c.length?c.wrapAll(a):b.append(a)})};F.has=function(a){var b=D(a)?function(b,d){return y(a,d).length}:function(b,d){return d.contains(a)};return this.filter(b)};F.is=function(a){var b=L(a);return x.call(this,function(a,d){return b.call(a,d,a)})};F.next=function(a,b,c){return M(G(P(O(this,"nextElementSibling",b,c))),a)}; 38 | F.nextAll=function(a){return this.next(a,!0)};F.nextUntil=function(a,b){return this.next(b,!0,a)};F.not=function(a){var b=L(a);return this.filter(function(c,d){return(!D(a)||B(d))&&!b.call(d,c,d)})};F.parent=function(a){return M(G(P(O(this,"parentNode"))),a)};F.index=function(a){var b=a?G(a)[0]:this[0];a=a?this:G(b).parent().children();return ea.call(a,b)};F.closest=function(a){var b=this.filter(a);if(b.length)return b;var c=this.parent();return c.length?c.closest(a):b}; 39 | F.parents=function(a,b){return M(G(P(O(this,"parentElement",!0,b))),a)};F.parentsUntil=function(a,b){return this.parents(b,a)};F.prev=function(a,b,c){return M(G(P(O(this,"previousElementSibling",b,c))),a)};F.prevAll=function(a){return this.prev(a,!0)};F.prevUntil=function(a,b){return this.prev(b,!0,a)};F.siblings=function(a){return M(G(P(O(this,function(a){return G(a).parent().children().not(a)}))),a)};"undefined"!==typeof exports?module.exports=G:n.cash=n.$=G; 40 | })(); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /lib/JSDOMParser.js: -------------------------------------------------------------------------------- 1 | /*eslint-env es6:false*/ 2 | /* This Source Code Form is subject to the terms of the Mozilla Public 3 | * License, v. 2.0. If a copy of the MPL was not distributed with this file, 4 | * You can obtain one at http://mozilla.org/MPL/2.0/. */ 5 | 6 | /** 7 | * This is a relatively lightweight DOMParser that is safe to use in a web 8 | * worker. This is far from a complete DOM implementation; however, it should 9 | * contain the minimal set of functionality necessary for Readability.js. 10 | * 11 | * Aside from not implementing the full DOM API, there are other quirks to be 12 | * aware of when using the JSDOMParser: 13 | * 14 | * 1) Properly formed HTML/XML must be used. This means you should be extra 15 | * careful when using this parser on anything received directly from an 16 | * XMLHttpRequest. Providing a serialized string from an XMLSerializer, 17 | * however, should be safe (since the browser's XMLSerializer should 18 | * generate valid HTML/XML). Therefore, if parsing a document from an XHR, 19 | * the recommended approach is to do the XHR in the main thread, use 20 | * XMLSerializer.serializeToString() on the responseXML, and pass the 21 | * resulting string to the worker. 22 | * 23 | * 2) Live NodeLists are not supported. DOM methods and properties such as 24 | * getElementsByTagName() and childNodes return standard arrays. If you 25 | * want these lists to be updated when nodes are removed or added to the 26 | * document, you must take care to manually update them yourself. 27 | */ 28 | (function (global) { 29 | 30 | // XML only defines these and the numeric ones: 31 | 32 | var entityTable = { 33 | "lt": "<", 34 | "gt": ">", 35 | "amp": "&", 36 | "quot": '"', 37 | "apos": "'", 38 | }; 39 | 40 | var reverseEntityTable = { 41 | "<": "<", 42 | ">": ">", 43 | "&": "&", 44 | '"': """, 45 | "'": "'", 46 | }; 47 | 48 | function encodeTextContentHTML(s) { 49 | return s.replace(/[&<>]/g, function(x) { 50 | return reverseEntityTable[x]; 51 | }); 52 | } 53 | 54 | function encodeHTML(s) { 55 | return s.replace(/[&<>'"]/g, function(x) { 56 | return reverseEntityTable[x]; 57 | }); 58 | } 59 | 60 | function decodeHTML(str) { 61 | return str.replace(/&(quot|amp|apos|lt|gt);/g, function(match, tag) { 62 | return entityTable[tag]; 63 | }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(match, hex, numStr) { 64 | var num = parseInt(hex || numStr, hex ? 16 : 10); // read num 65 | return String.fromCharCode(num); 66 | }); 67 | } 68 | 69 | // When a style is set in JS, map it to the corresponding CSS attribute 70 | var styleMap = { 71 | "alignmentBaseline": "alignment-baseline", 72 | "background": "background", 73 | "backgroundAttachment": "background-attachment", 74 | "backgroundClip": "background-clip", 75 | "backgroundColor": "background-color", 76 | "backgroundImage": "background-image", 77 | "backgroundOrigin": "background-origin", 78 | "backgroundPosition": "background-position", 79 | "backgroundPositionX": "background-position-x", 80 | "backgroundPositionY": "background-position-y", 81 | "backgroundRepeat": "background-repeat", 82 | "backgroundRepeatX": "background-repeat-x", 83 | "backgroundRepeatY": "background-repeat-y", 84 | "backgroundSize": "background-size", 85 | "baselineShift": "baseline-shift", 86 | "border": "border", 87 | "borderBottom": "border-bottom", 88 | "borderBottomColor": "border-bottom-color", 89 | "borderBottomLeftRadius": "border-bottom-left-radius", 90 | "borderBottomRightRadius": "border-bottom-right-radius", 91 | "borderBottomStyle": "border-bottom-style", 92 | "borderBottomWidth": "border-bottom-width", 93 | "borderCollapse": "border-collapse", 94 | "borderColor": "border-color", 95 | "borderImage": "border-image", 96 | "borderImageOutset": "border-image-outset", 97 | "borderImageRepeat": "border-image-repeat", 98 | "borderImageSlice": "border-image-slice", 99 | "borderImageSource": "border-image-source", 100 | "borderImageWidth": "border-image-width", 101 | "borderLeft": "border-left", 102 | "borderLeftColor": "border-left-color", 103 | "borderLeftStyle": "border-left-style", 104 | "borderLeftWidth": "border-left-width", 105 | "borderRadius": "border-radius", 106 | "borderRight": "border-right", 107 | "borderRightColor": "border-right-color", 108 | "borderRightStyle": "border-right-style", 109 | "borderRightWidth": "border-right-width", 110 | "borderSpacing": "border-spacing", 111 | "borderStyle": "border-style", 112 | "borderTop": "border-top", 113 | "borderTopColor": "border-top-color", 114 | "borderTopLeftRadius": "border-top-left-radius", 115 | "borderTopRightRadius": "border-top-right-radius", 116 | "borderTopStyle": "border-top-style", 117 | "borderTopWidth": "border-top-width", 118 | "borderWidth": "border-width", 119 | "bottom": "bottom", 120 | "boxShadow": "box-shadow", 121 | "boxSizing": "box-sizing", 122 | "captionSide": "caption-side", 123 | "clear": "clear", 124 | "clip": "clip", 125 | "clipPath": "clip-path", 126 | "clipRule": "clip-rule", 127 | "color": "color", 128 | "colorInterpolation": "color-interpolation", 129 | "colorInterpolationFilters": "color-interpolation-filters", 130 | "colorProfile": "color-profile", 131 | "colorRendering": "color-rendering", 132 | "content": "content", 133 | "counterIncrement": "counter-increment", 134 | "counterReset": "counter-reset", 135 | "cursor": "cursor", 136 | "direction": "direction", 137 | "display": "display", 138 | "dominantBaseline": "dominant-baseline", 139 | "emptyCells": "empty-cells", 140 | "enableBackground": "enable-background", 141 | "fill": "fill", 142 | "fillOpacity": "fill-opacity", 143 | "fillRule": "fill-rule", 144 | "filter": "filter", 145 | "cssFloat": "float", 146 | "floodColor": "flood-color", 147 | "floodOpacity": "flood-opacity", 148 | "font": "font", 149 | "fontFamily": "font-family", 150 | "fontSize": "font-size", 151 | "fontStretch": "font-stretch", 152 | "fontStyle": "font-style", 153 | "fontVariant": "font-variant", 154 | "fontWeight": "font-weight", 155 | "glyphOrientationHorizontal": "glyph-orientation-horizontal", 156 | "glyphOrientationVertical": "glyph-orientation-vertical", 157 | "height": "height", 158 | "imageRendering": "image-rendering", 159 | "kerning": "kerning", 160 | "left": "left", 161 | "letterSpacing": "letter-spacing", 162 | "lightingColor": "lighting-color", 163 | "lineHeight": "line-height", 164 | "listStyle": "list-style", 165 | "listStyleImage": "list-style-image", 166 | "listStylePosition": "list-style-position", 167 | "listStyleType": "list-style-type", 168 | "margin": "margin", 169 | "marginBottom": "margin-bottom", 170 | "marginLeft": "margin-left", 171 | "marginRight": "margin-right", 172 | "marginTop": "margin-top", 173 | "marker": "marker", 174 | "markerEnd": "marker-end", 175 | "markerMid": "marker-mid", 176 | "markerStart": "marker-start", 177 | "mask": "mask", 178 | "maxHeight": "max-height", 179 | "maxWidth": "max-width", 180 | "minHeight": "min-height", 181 | "minWidth": "min-width", 182 | "opacity": "opacity", 183 | "orphans": "orphans", 184 | "outline": "outline", 185 | "outlineColor": "outline-color", 186 | "outlineOffset": "outline-offset", 187 | "outlineStyle": "outline-style", 188 | "outlineWidth": "outline-width", 189 | "overflow": "overflow", 190 | "overflowX": "overflow-x", 191 | "overflowY": "overflow-y", 192 | "padding": "padding", 193 | "paddingBottom": "padding-bottom", 194 | "paddingLeft": "padding-left", 195 | "paddingRight": "padding-right", 196 | "paddingTop": "padding-top", 197 | "page": "page", 198 | "pageBreakAfter": "page-break-after", 199 | "pageBreakBefore": "page-break-before", 200 | "pageBreakInside": "page-break-inside", 201 | "pointerEvents": "pointer-events", 202 | "position": "position", 203 | "quotes": "quotes", 204 | "resize": "resize", 205 | "right": "right", 206 | "shapeRendering": "shape-rendering", 207 | "size": "size", 208 | "speak": "speak", 209 | "src": "src", 210 | "stopColor": "stop-color", 211 | "stopOpacity": "stop-opacity", 212 | "stroke": "stroke", 213 | "strokeDasharray": "stroke-dasharray", 214 | "strokeDashoffset": "stroke-dashoffset", 215 | "strokeLinecap": "stroke-linecap", 216 | "strokeLinejoin": "stroke-linejoin", 217 | "strokeMiterlimit": "stroke-miterlimit", 218 | "strokeOpacity": "stroke-opacity", 219 | "strokeWidth": "stroke-width", 220 | "tableLayout": "table-layout", 221 | "textAlign": "text-align", 222 | "textAnchor": "text-anchor", 223 | "textDecoration": "text-decoration", 224 | "textIndent": "text-indent", 225 | "textLineThrough": "text-line-through", 226 | "textLineThroughColor": "text-line-through-color", 227 | "textLineThroughMode": "text-line-through-mode", 228 | "textLineThroughStyle": "text-line-through-style", 229 | "textLineThroughWidth": "text-line-through-width", 230 | "textOverflow": "text-overflow", 231 | "textOverline": "text-overline", 232 | "textOverlineColor": "text-overline-color", 233 | "textOverlineMode": "text-overline-mode", 234 | "textOverlineStyle": "text-overline-style", 235 | "textOverlineWidth": "text-overline-width", 236 | "textRendering": "text-rendering", 237 | "textShadow": "text-shadow", 238 | "textTransform": "text-transform", 239 | "textUnderline": "text-underline", 240 | "textUnderlineColor": "text-underline-color", 241 | "textUnderlineMode": "text-underline-mode", 242 | "textUnderlineStyle": "text-underline-style", 243 | "textUnderlineWidth": "text-underline-width", 244 | "top": "top", 245 | "unicodeBidi": "unicode-bidi", 246 | "unicodeRange": "unicode-range", 247 | "vectorEffect": "vector-effect", 248 | "verticalAlign": "vertical-align", 249 | "visibility": "visibility", 250 | "whiteSpace": "white-space", 251 | "widows": "widows", 252 | "width": "width", 253 | "wordBreak": "word-break", 254 | "wordSpacing": "word-spacing", 255 | "wordWrap": "word-wrap", 256 | "writingMode": "writing-mode", 257 | "zIndex": "z-index", 258 | "zoom": "zoom", 259 | }; 260 | 261 | // Elements that can be self-closing 262 | var voidElems = { 263 | "area": true, 264 | "base": true, 265 | "br": true, 266 | "col": true, 267 | "command": true, 268 | "embed": true, 269 | "hr": true, 270 | "img": true, 271 | "input": true, 272 | "link": true, 273 | "meta": true, 274 | "param": true, 275 | "source": true, 276 | "wbr": true 277 | }; 278 | 279 | var whitespace = [" ", "\t", "\n", "\r"]; 280 | 281 | // See https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType 282 | var nodeTypes = { 283 | ELEMENT_NODE: 1, 284 | ATTRIBUTE_NODE: 2, 285 | TEXT_NODE: 3, 286 | CDATA_SECTION_NODE: 4, 287 | ENTITY_REFERENCE_NODE: 5, 288 | ENTITY_NODE: 6, 289 | PROCESSING_INSTRUCTION_NODE: 7, 290 | COMMENT_NODE: 8, 291 | DOCUMENT_NODE: 9, 292 | DOCUMENT_TYPE_NODE: 10, 293 | DOCUMENT_FRAGMENT_NODE: 11, 294 | NOTATION_NODE: 12 295 | }; 296 | 297 | function getElementsByTagName(tag) { 298 | tag = tag.toUpperCase(); 299 | var elems = []; 300 | var allTags = (tag === "*"); 301 | function getElems(node) { 302 | var length = node.children.length; 303 | for (var i = 0; i < length; i++) { 304 | var child = node.children[i]; 305 | if (allTags || (child.tagName === tag)) 306 | elems.push(child); 307 | getElems(child); 308 | } 309 | } 310 | getElems(this); 311 | elems._isLiveNodeList = true; 312 | return elems; 313 | } 314 | 315 | var Node = function () {}; 316 | 317 | Node.prototype = { 318 | attributes: null, 319 | childNodes: null, 320 | localName: null, 321 | nodeName: null, 322 | parentNode: null, 323 | textContent: null, 324 | nextSibling: null, 325 | previousSibling: null, 326 | 327 | get firstChild() { 328 | return this.childNodes[0] || null; 329 | }, 330 | 331 | get firstElementChild() { 332 | return this.children[0] || null; 333 | }, 334 | 335 | get lastChild() { 336 | return this.childNodes[this.childNodes.length - 1] || null; 337 | }, 338 | 339 | get lastElementChild() { 340 | return this.children[this.children.length - 1] || null; 341 | }, 342 | 343 | appendChild: function (child) { 344 | if (child.parentNode) { 345 | child.parentNode.removeChild(child); 346 | } 347 | 348 | var last = this.lastChild; 349 | if (last) 350 | last.nextSibling = child; 351 | child.previousSibling = last; 352 | 353 | if (child.nodeType === Node.ELEMENT_NODE) { 354 | child.previousElementSibling = this.children[this.children.length - 1] || null; 355 | this.children.push(child); 356 | child.previousElementSibling && (child.previousElementSibling.nextElementSibling = child); 357 | } 358 | this.childNodes.push(child); 359 | child.parentNode = this; 360 | }, 361 | 362 | removeChild: function (child) { 363 | var childNodes = this.childNodes; 364 | var childIndex = childNodes.indexOf(child); 365 | if (childIndex === -1) { 366 | throw "removeChild: node not found"; 367 | } else { 368 | child.parentNode = null; 369 | var prev = child.previousSibling; 370 | var next = child.nextSibling; 371 | if (prev) 372 | prev.nextSibling = next; 373 | if (next) 374 | next.previousSibling = prev; 375 | 376 | if (child.nodeType === Node.ELEMENT_NODE) { 377 | prev = child.previousElementSibling; 378 | next = child.nextElementSibling; 379 | if (prev) 380 | prev.nextElementSibling = next; 381 | if (next) 382 | next.previousElementSibling = prev; 383 | this.children.splice(this.children.indexOf(child), 1); 384 | } 385 | 386 | child.previousSibling = child.nextSibling = null; 387 | child.previousElementSibling = child.nextElementSibling = null; 388 | 389 | return childNodes.splice(childIndex, 1)[0]; 390 | } 391 | }, 392 | 393 | replaceChild: function (newNode, oldNode) { 394 | var childNodes = this.childNodes; 395 | var childIndex = childNodes.indexOf(oldNode); 396 | if (childIndex === -1) { 397 | throw "replaceChild: node not found"; 398 | } else { 399 | // This will take care of updating the new node if it was somewhere else before: 400 | if (newNode.parentNode) 401 | newNode.parentNode.removeChild(newNode); 402 | 403 | childNodes[childIndex] = newNode; 404 | 405 | // update the new node's sibling properties, and its new siblings' sibling properties 406 | newNode.nextSibling = oldNode.nextSibling; 407 | newNode.previousSibling = oldNode.previousSibling; 408 | if (newNode.nextSibling) 409 | newNode.nextSibling.previousSibling = newNode; 410 | if (newNode.previousSibling) 411 | newNode.previousSibling.nextSibling = newNode; 412 | 413 | newNode.parentNode = this; 414 | 415 | // Now deal with elements before we clear out those values for the old node, 416 | // because it can help us take shortcuts here: 417 | if (newNode.nodeType === Node.ELEMENT_NODE) { 418 | if (oldNode.nodeType === Node.ELEMENT_NODE) { 419 | // Both were elements, which makes this easier, we just swap things out: 420 | newNode.previousElementSibling = oldNode.previousElementSibling; 421 | newNode.nextElementSibling = oldNode.nextElementSibling; 422 | if (newNode.previousElementSibling) 423 | newNode.previousElementSibling.nextElementSibling = newNode; 424 | if (newNode.nextElementSibling) 425 | newNode.nextElementSibling.previousElementSibling = newNode; 426 | this.children[this.children.indexOf(oldNode)] = newNode; 427 | } else { 428 | // Hard way: 429 | newNode.previousElementSibling = (function() { 430 | for (var i = childIndex - 1; i >= 0; i--) { 431 | if (childNodes[i].nodeType === Node.ELEMENT_NODE) 432 | return childNodes[i]; 433 | } 434 | return null; 435 | })(); 436 | if (newNode.previousElementSibling) { 437 | newNode.nextElementSibling = newNode.previousElementSibling.nextElementSibling; 438 | } else { 439 | newNode.nextElementSibling = (function() { 440 | for (var i = childIndex + 1; i < childNodes.length; i++) { 441 | if (childNodes[i].nodeType === Node.ELEMENT_NODE) 442 | return childNodes[i]; 443 | } 444 | return null; 445 | })(); 446 | } 447 | if (newNode.previousElementSibling) 448 | newNode.previousElementSibling.nextElementSibling = newNode; 449 | if (newNode.nextElementSibling) 450 | newNode.nextElementSibling.previousElementSibling = newNode; 451 | 452 | if (newNode.nextElementSibling) 453 | this.children.splice(this.children.indexOf(newNode.nextElementSibling), 0, newNode); 454 | else 455 | this.children.push(newNode); 456 | } 457 | } else if (oldNode.nodeType === Node.ELEMENT_NODE) { 458 | // new node is not an element node. 459 | // if the old one was, update its element siblings: 460 | if (oldNode.previousElementSibling) 461 | oldNode.previousElementSibling.nextElementSibling = oldNode.nextElementSibling; 462 | if (oldNode.nextElementSibling) 463 | oldNode.nextElementSibling.previousElementSibling = oldNode.previousElementSibling; 464 | this.children.splice(this.children.indexOf(oldNode), 1); 465 | 466 | // If the old node wasn't an element, neither the new nor the old node was an element, 467 | // and the children array and its members shouldn't need any updating. 468 | } 469 | 470 | 471 | oldNode.parentNode = null; 472 | oldNode.previousSibling = null; 473 | oldNode.nextSibling = null; 474 | if (oldNode.nodeType === Node.ELEMENT_NODE) { 475 | oldNode.previousElementSibling = null; 476 | oldNode.nextElementSibling = null; 477 | } 478 | return oldNode; 479 | } 480 | }, 481 | 482 | __JSDOMParser__: true, 483 | }; 484 | 485 | for (var nodeType in nodeTypes) { 486 | Node[nodeType] = Node.prototype[nodeType] = nodeTypes[nodeType]; 487 | } 488 | 489 | var Attribute = function (name, value) { 490 | this.name = name; 491 | this._value = value; 492 | }; 493 | 494 | Attribute.prototype = { 495 | get value() { 496 | return this._value; 497 | }, 498 | setValue: function(newValue) { 499 | this._value = newValue; 500 | }, 501 | getEncodedValue: function() { 502 | return encodeHTML(this._value); 503 | }, 504 | }; 505 | 506 | var Comment = function () { 507 | this.childNodes = []; 508 | }; 509 | 510 | Comment.prototype = { 511 | __proto__: Node.prototype, 512 | 513 | nodeName: "#comment", 514 | nodeType: Node.COMMENT_NODE 515 | }; 516 | 517 | var Text = function () { 518 | this.childNodes = []; 519 | }; 520 | 521 | Text.prototype = { 522 | __proto__: Node.prototype, 523 | 524 | nodeName: "#text", 525 | nodeType: Node.TEXT_NODE, 526 | get textContent() { 527 | if (typeof this._textContent === "undefined") { 528 | this._textContent = decodeHTML(this._innerHTML || ""); 529 | } 530 | return this._textContent; 531 | }, 532 | get innerHTML() { 533 | if (typeof this._innerHTML === "undefined") { 534 | this._innerHTML = encodeTextContentHTML(this._textContent || ""); 535 | } 536 | return this._innerHTML; 537 | }, 538 | 539 | set innerHTML(newHTML) { 540 | this._innerHTML = newHTML; 541 | delete this._textContent; 542 | }, 543 | set textContent(newText) { 544 | this._textContent = newText; 545 | delete this._innerHTML; 546 | }, 547 | }; 548 | 549 | var Document = function (url) { 550 | this.documentURI = url; 551 | this.styleSheets = []; 552 | this.childNodes = []; 553 | this.children = []; 554 | }; 555 | 556 | Document.prototype = { 557 | __proto__: Node.prototype, 558 | 559 | nodeName: "#document", 560 | nodeType: Node.DOCUMENT_NODE, 561 | title: "", 562 | 563 | getElementsByTagName: getElementsByTagName, 564 | 565 | getElementById: function (id) { 566 | function getElem(node) { 567 | var length = node.children.length; 568 | if (node.id === id) 569 | return node; 570 | for (var i = 0; i < length; i++) { 571 | var el = getElem(node.children[i]); 572 | if (el) 573 | return el; 574 | } 575 | return null; 576 | } 577 | return getElem(this); 578 | }, 579 | 580 | createElement: function (tag) { 581 | var node = new Element(tag); 582 | return node; 583 | }, 584 | 585 | createTextNode: function (text) { 586 | var node = new Text(); 587 | node.textContent = text; 588 | return node; 589 | }, 590 | 591 | get baseURI() { 592 | if (!this.hasOwnProperty("_baseURI")) { 593 | this._baseURI = this.documentURI; 594 | var baseElements = this.getElementsByTagName("base"); 595 | var href = baseElements[0] && baseElements[0].getAttribute("href"); 596 | if (href) { 597 | try { 598 | this._baseURI = (new URL(href, this._baseURI)).href; 599 | } catch (ex) {/* Just fall back to documentURI */} 600 | } 601 | } 602 | return this._baseURI; 603 | }, 604 | }; 605 | 606 | var Element = function (tag) { 607 | // We use this to find the closing tag. 608 | this._matchingTag = tag; 609 | // We're explicitly a non-namespace aware parser, we just pretend it's all HTML. 610 | var lastColonIndex = tag.lastIndexOf(":"); 611 | if (lastColonIndex != -1) { 612 | tag = tag.substring(lastColonIndex + 1); 613 | } 614 | this.attributes = []; 615 | this.childNodes = []; 616 | this.children = []; 617 | this.nextElementSibling = this.previousElementSibling = null; 618 | this.localName = tag.toLowerCase(); 619 | this.tagName = tag.toUpperCase(); 620 | this.style = new Style(this); 621 | }; 622 | 623 | Element.prototype = { 624 | __proto__: Node.prototype, 625 | 626 | nodeType: Node.ELEMENT_NODE, 627 | 628 | getElementsByTagName: getElementsByTagName, 629 | 630 | get className() { 631 | return this.getAttribute("class") || ""; 632 | }, 633 | 634 | set className(str) { 635 | this.setAttribute("class", str); 636 | }, 637 | 638 | get id() { 639 | return this.getAttribute("id") || ""; 640 | }, 641 | 642 | set id(str) { 643 | this.setAttribute("id", str); 644 | }, 645 | 646 | get href() { 647 | return this.getAttribute("href") || ""; 648 | }, 649 | 650 | set href(str) { 651 | this.setAttribute("href", str); 652 | }, 653 | 654 | get src() { 655 | return this.getAttribute("src") || ""; 656 | }, 657 | 658 | set src(str) { 659 | this.setAttribute("src", str); 660 | }, 661 | 662 | get srcset() { 663 | return this.getAttribute("srcset") || ""; 664 | }, 665 | 666 | set srcset(str) { 667 | this.setAttribute("srcset", str); 668 | }, 669 | 670 | get nodeName() { 671 | return this.tagName; 672 | }, 673 | 674 | get innerHTML() { 675 | function getHTML(node) { 676 | var i = 0; 677 | for (i = 0; i < node.childNodes.length; i++) { 678 | var child = node.childNodes[i]; 679 | if (child.localName) { 680 | arr.push("<" + child.localName); 681 | 682 | // serialize attribute list 683 | for (var j = 0; j < child.attributes.length; j++) { 684 | var attr = child.attributes[j]; 685 | // the attribute value will be HTML escaped. 686 | var val = attr.getEncodedValue(); 687 | var quote = (val.indexOf('"') === -1 ? '"' : "'"); 688 | arr.push(" " + attr.name + "=" + quote + val + quote); 689 | } 690 | 691 | if (child.localName in voidElems && !child.childNodes.length) { 692 | // if this is a self-closing element, end it here 693 | arr.push("/>"); 694 | } else { 695 | // otherwise, add its children 696 | arr.push(">"); 697 | getHTML(child); 698 | arr.push(""); 699 | } 700 | } else { 701 | // This is a text node, so asking for innerHTML won't recurse. 702 | arr.push(child.innerHTML); 703 | } 704 | } 705 | } 706 | 707 | // Using Array.join() avoids the overhead from lazy string concatenation. 708 | var arr = []; 709 | getHTML(this); 710 | return arr.join(""); 711 | }, 712 | 713 | set innerHTML(html) { 714 | var parser = new JSDOMParser(); 715 | var node = parser.parse(html); 716 | var i; 717 | for (i = this.childNodes.length; --i >= 0;) { 718 | this.childNodes[i].parentNode = null; 719 | } 720 | this.childNodes = node.childNodes; 721 | this.children = node.children; 722 | for (i = this.childNodes.length; --i >= 0;) { 723 | this.childNodes[i].parentNode = this; 724 | } 725 | }, 726 | 727 | set textContent(text) { 728 | // clear parentNodes for existing children 729 | for (var i = this.childNodes.length; --i >= 0;) { 730 | this.childNodes[i].parentNode = null; 731 | } 732 | 733 | var node = new Text(); 734 | this.childNodes = [ node ]; 735 | this.children = []; 736 | node.textContent = text; 737 | node.parentNode = this; 738 | }, 739 | 740 | get textContent() { 741 | function getText(node) { 742 | var nodes = node.childNodes; 743 | for (var i = 0; i < nodes.length; i++) { 744 | var child = nodes[i]; 745 | if (child.nodeType === 3) { 746 | text.push(child.textContent); 747 | } else { 748 | getText(child); 749 | } 750 | } 751 | } 752 | 753 | // Using Array.join() avoids the overhead from lazy string concatenation. 754 | // See http://blog.cdleary.com/2012/01/string-representation-in-spidermonkey/#ropes 755 | var text = []; 756 | getText(this); 757 | return text.join(""); 758 | }, 759 | 760 | getAttribute: function (name) { 761 | for (var i = this.attributes.length; --i >= 0;) { 762 | var attr = this.attributes[i]; 763 | if (attr.name === name) { 764 | return attr.value; 765 | } 766 | } 767 | return undefined; 768 | }, 769 | 770 | setAttribute: function (name, value) { 771 | for (var i = this.attributes.length; --i >= 0;) { 772 | var attr = this.attributes[i]; 773 | if (attr.name === name) { 774 | attr.setValue(value); 775 | return; 776 | } 777 | } 778 | this.attributes.push(new Attribute(name, value)); 779 | }, 780 | 781 | removeAttribute: function (name) { 782 | for (var i = this.attributes.length; --i >= 0;) { 783 | var attr = this.attributes[i]; 784 | if (attr.name === name) { 785 | this.attributes.splice(i, 1); 786 | break; 787 | } 788 | } 789 | }, 790 | 791 | hasAttribute: function (name) { 792 | return this.attributes.some(function (attr) { 793 | return attr.name == name; 794 | }); 795 | }, 796 | }; 797 | 798 | var Style = function (node) { 799 | this.node = node; 800 | }; 801 | 802 | // getStyle() and setStyle() use the style attribute string directly. This 803 | // won't be very efficient if there are a lot of style manipulations, but 804 | // it's the easiest way to make sure the style attribute string and the JS 805 | // style property stay in sync. Readability.js doesn't do many style 806 | // manipulations, so this should be okay. 807 | Style.prototype = { 808 | getStyle: function (styleName) { 809 | var attr = this.node.getAttribute("style"); 810 | if (!attr) 811 | return undefined; 812 | 813 | var styles = attr.split(";"); 814 | for (var i = 0; i < styles.length; i++) { 815 | var style = styles[i].split(":"); 816 | var name = style[0].trim(); 817 | if (name === styleName) 818 | return style[1].trim(); 819 | } 820 | 821 | return undefined; 822 | }, 823 | 824 | setStyle: function (styleName, styleValue) { 825 | var value = this.node.getAttribute("style") || ""; 826 | var index = 0; 827 | do { 828 | var next = value.indexOf(";", index) + 1; 829 | var length = next - index - 1; 830 | var style = (length > 0 ? value.substr(index, length) : value.substr(index)); 831 | if (style.substr(0, style.indexOf(":")).trim() === styleName) { 832 | value = value.substr(0, index).trim() + (next ? " " + value.substr(next).trim() : ""); 833 | break; 834 | } 835 | index = next; 836 | } while (index); 837 | 838 | value += " " + styleName + ": " + styleValue + ";"; 839 | this.node.setAttribute("style", value.trim()); 840 | } 841 | }; 842 | 843 | // For each item in styleMap, define a getter and setter on the style 844 | // property. 845 | for (var jsName in styleMap) { 846 | (function (cssName) { 847 | Style.prototype.__defineGetter__(jsName, function () { 848 | return this.getStyle(cssName); 849 | }); 850 | Style.prototype.__defineSetter__(jsName, function (value) { 851 | this.setStyle(cssName, value); 852 | }); 853 | })(styleMap[jsName]); 854 | } 855 | 856 | var JSDOMParser = function () { 857 | this.currentChar = 0; 858 | 859 | // In makeElementNode() we build up many strings one char at a time. Using 860 | // += for this results in lots of short-lived intermediate strings. It's 861 | // better to build an array of single-char strings and then join() them 862 | // together at the end. And reusing a single array (i.e. |this.strBuf|) 863 | // over and over for this purpose uses less memory than using a new array 864 | // for each string. 865 | this.strBuf = []; 866 | 867 | // Similarly, we reuse this array to return the two arguments from 868 | // makeElementNode(), which saves us from having to allocate a new array 869 | // every time. 870 | this.retPair = []; 871 | 872 | this.errorState = ""; 873 | }; 874 | 875 | JSDOMParser.prototype = { 876 | error: function(m) { 877 | if (typeof dump !== "undefined") { 878 | dump("JSDOMParser error: " + m + "\n"); 879 | } else if (typeof console !== "undefined") { 880 | console.log("JSDOMParser error: " + m + "\n"); 881 | } 882 | this.errorState += m + "\n"; 883 | }, 884 | 885 | /** 886 | * Look at the next character without advancing the index. 887 | */ 888 | peekNext: function () { 889 | return this.html[this.currentChar]; 890 | }, 891 | 892 | /** 893 | * Get the next character and advance the index. 894 | */ 895 | nextChar: function () { 896 | return this.html[this.currentChar++]; 897 | }, 898 | 899 | /** 900 | * Called after a quote character is read. This finds the next quote 901 | * character and returns the text string in between. 902 | */ 903 | readString: function (quote) { 904 | var str; 905 | var n = this.html.indexOf(quote, this.currentChar); 906 | if (n === -1) { 907 | this.currentChar = this.html.length; 908 | str = null; 909 | } else { 910 | str = this.html.substring(this.currentChar, n); 911 | this.currentChar = n + 1; 912 | } 913 | 914 | return str; 915 | }, 916 | 917 | /** 918 | * Called when parsing a node. This finds the next name/value attribute 919 | * pair and adds the result to the attributes list. 920 | */ 921 | readAttribute: function (node) { 922 | var name = ""; 923 | 924 | var n = this.html.indexOf("=", this.currentChar); 925 | if (n === -1) { 926 | this.currentChar = this.html.length; 927 | } else { 928 | // Read until a '=' character is hit; this will be the attribute key 929 | name = this.html.substring(this.currentChar, n); 930 | this.currentChar = n + 1; 931 | } 932 | 933 | if (!name) 934 | return; 935 | 936 | // After a '=', we should see a '"' for the attribute value 937 | var c = this.nextChar(); 938 | if (c !== '"' && c !== "'") { 939 | this.error("Error reading attribute " + name + ", expecting '\"'"); 940 | return; 941 | } 942 | 943 | // Read the attribute value (and consume the matching quote) 944 | var value = this.readString(c); 945 | 946 | node.attributes.push(new Attribute(name, decodeHTML(value))); 947 | 948 | return; 949 | }, 950 | 951 | /** 952 | * Parses and returns an Element node. This is called after a '<' has been 953 | * read. 954 | * 955 | * @returns an array; the first index of the array is the parsed node; 956 | * the second index is a boolean indicating whether this is a void 957 | * Element 958 | */ 959 | makeElementNode: function (retPair) { 960 | var c = this.nextChar(); 961 | 962 | // Read the Element tag name 963 | var strBuf = this.strBuf; 964 | strBuf.length = 0; 965 | while (whitespace.indexOf(c) == -1 && c !== ">" && c !== "/") { 966 | if (c === undefined) 967 | return false; 968 | strBuf.push(c); 969 | c = this.nextChar(); 970 | } 971 | var tag = strBuf.join(""); 972 | 973 | if (!tag) 974 | return false; 975 | 976 | var node = new Element(tag); 977 | 978 | // Read Element attributes 979 | while (c !== "/" && c !== ">") { 980 | if (c === undefined) 981 | return false; 982 | while (whitespace.indexOf(this.html[this.currentChar++]) != -1) { 983 | // Advance cursor to first non-whitespace char. 984 | } 985 | this.currentChar--; 986 | c = this.nextChar(); 987 | if (c !== "/" && c !== ">") { 988 | --this.currentChar; 989 | this.readAttribute(node); 990 | } 991 | } 992 | 993 | // If this is a self-closing tag, read '/>' 994 | var closed = false; 995 | if (c === "/") { 996 | closed = true; 997 | c = this.nextChar(); 998 | if (c !== ">") { 999 | this.error("expected '>' to close " + tag); 1000 | return false; 1001 | } 1002 | } 1003 | 1004 | retPair[0] = node; 1005 | retPair[1] = closed; 1006 | return true; 1007 | }, 1008 | 1009 | /** 1010 | * If the current input matches this string, advance the input index; 1011 | * otherwise, do nothing. 1012 | * 1013 | * @returns whether input matched string 1014 | */ 1015 | match: function (str) { 1016 | var strlen = str.length; 1017 | if (this.html.substr(this.currentChar, strlen).toLowerCase() === str.toLowerCase()) { 1018 | this.currentChar += strlen; 1019 | return true; 1020 | } 1021 | return false; 1022 | }, 1023 | 1024 | /** 1025 | * Searches the input until a string is found and discards all input up to 1026 | * and including the matched string. 1027 | */ 1028 | discardTo: function (str) { 1029 | var index = this.html.indexOf(str, this.currentChar) + str.length; 1030 | if (index === -1) 1031 | this.currentChar = this.html.length; 1032 | this.currentChar = index; 1033 | }, 1034 | 1035 | /** 1036 | * Reads child nodes for the given node. 1037 | */ 1038 | readChildren: function (node) { 1039 | var child; 1040 | while ((child = this.readNode())) { 1041 | // Don't keep Comment nodes 1042 | if (child.nodeType !== 8) { 1043 | node.appendChild(child); 1044 | } 1045 | } 1046 | }, 1047 | 1048 | discardNextComment: function() { 1049 | if (this.match("--")) { 1050 | this.discardTo("-->"); 1051 | } else { 1052 | var c = this.nextChar(); 1053 | while (c !== ">") { 1054 | if (c === undefined) 1055 | return null; 1056 | if (c === '"' || c === "'") 1057 | this.readString(c); 1058 | c = this.nextChar(); 1059 | } 1060 | } 1061 | return new Comment(); 1062 | }, 1063 | 1064 | 1065 | /** 1066 | * Reads the next child node from the input. If we're reading a closing 1067 | * tag, or if we've reached the end of input, return null. 1068 | * 1069 | * @returns the node 1070 | */ 1071 | readNode: function () { 1072 | var c = this.nextChar(); 1073 | 1074 | if (c === undefined) 1075 | return null; 1076 | 1077 | // Read any text as Text node 1078 | var textNode; 1079 | if (c !== "<") { 1080 | --this.currentChar; 1081 | textNode = new Text(); 1082 | var n = this.html.indexOf("<", this.currentChar); 1083 | if (n === -1) { 1084 | textNode.innerHTML = this.html.substring(this.currentChar, this.html.length); 1085 | this.currentChar = this.html.length; 1086 | } else { 1087 | textNode.innerHTML = this.html.substring(this.currentChar, n); 1088 | this.currentChar = n; 1089 | } 1090 | return textNode; 1091 | } 1092 | 1093 | if (this.match("![CDATA[")) { 1094 | var endChar = this.html.indexOf("]]>", this.currentChar); 1095 | if (endChar === -1) { 1096 | this.error("unclosed CDATA section"); 1097 | return null; 1098 | } 1099 | textNode = new Text(); 1100 | textNode.textContent = this.html.substring(this.currentChar, endChar); 1101 | this.currentChar = endChar + ("]]>").length; 1102 | return textNode; 1103 | } 1104 | 1105 | c = this.peekNext(); 1106 | 1107 | // Read Comment node. Normally, Comment nodes know their inner 1108 | // textContent, but we don't really care about Comment nodes (we throw 1109 | // them away in readChildren()). So just returning an empty Comment node 1110 | // here is sufficient. 1111 | if (c === "!" || c === "?") { 1112 | // We're still before the ! or ? that is starting this comment: 1113 | this.currentChar++; 1114 | return this.discardNextComment(); 1115 | } 1116 | 1117 | // If we're reading a closing tag, return null. This means we've reached 1118 | // the end of this set of child nodes. 1119 | if (c === "/") { 1120 | --this.currentChar; 1121 | return null; 1122 | } 1123 | 1124 | // Otherwise, we're looking at an Element node 1125 | var result = this.makeElementNode(this.retPair); 1126 | if (!result) 1127 | return null; 1128 | 1129 | var node = this.retPair[0]; 1130 | var closed = this.retPair[1]; 1131 | var localName = node.localName; 1132 | 1133 | // If this isn't a void Element, read its child nodes 1134 | if (!closed) { 1135 | this.readChildren(node); 1136 | var closingTag = ""; 1137 | if (!this.match(closingTag)) { 1138 | this.error("expected '" + closingTag + "' and got " + this.html.substr(this.currentChar, closingTag.length)); 1139 | return null; 1140 | } 1141 | } 1142 | 1143 | // Only use the first title, because SVG might have other 1144 | // title elements which we don't care about (medium.com 1145 | // does this, at least). 1146 | if (localName === "title" && !this.doc.title) { 1147 | this.doc.title = node.textContent.trim(); 1148 | } else if (localName === "head") { 1149 | this.doc.head = node; 1150 | } else if (localName === "body") { 1151 | this.doc.body = node; 1152 | } else if (localName === "html") { 1153 | this.doc.documentElement = node; 1154 | } 1155 | 1156 | return node; 1157 | }, 1158 | 1159 | /** 1160 | * Parses an HTML string and returns a JS implementation of the Document. 1161 | */ 1162 | parse: function (html, url) { 1163 | this.html = html; 1164 | var doc = this.doc = new Document(url); 1165 | this.readChildren(doc); 1166 | 1167 | // If this is an HTML document, remove root-level children except for the 1168 | // node 1169 | if (doc.documentElement) { 1170 | for (var i = doc.childNodes.length; --i >= 0;) { 1171 | var child = doc.childNodes[i]; 1172 | if (child !== doc.documentElement) { 1173 | doc.removeChild(child); 1174 | } 1175 | } 1176 | } 1177 | 1178 | return doc; 1179 | } 1180 | }; 1181 | 1182 | // Attach the standard DOM types to the global scope 1183 | global.Node = Node; 1184 | global.Comment = Comment; 1185 | global.Document = Document; 1186 | global.Element = Element; 1187 | global.Text = Text; 1188 | 1189 | // Attach JSDOMParser to the global scope 1190 | global.JSDOMParser = JSDOMParser; 1191 | 1192 | })(this); 1193 | 1194 | if (typeof module === "object") { 1195 | module.exports = this.JSDOMParser; 1196 | } 1197 | -------------------------------------------------------------------------------- /lib/browser-polyfill.js: -------------------------------------------------------------------------------- 1 | (function (global, factory) { 2 | if (typeof define === "function" && define.amd) { 3 | define("webextension-polyfill", ["module"], factory); 4 | } else if (typeof exports !== "undefined") { 5 | factory(module); 6 | } else { 7 | var mod = { 8 | exports: {} 9 | }; 10 | factory(mod); 11 | global.browser = mod.exports; 12 | } 13 | })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (module) { 14 | /* webextension-polyfill - v0.6.0 - Mon Dec 23 2019 12:32:53 */ 15 | 16 | /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ 17 | 18 | /* vim: set sts=2 sw=2 et tw=80: */ 19 | 20 | /* This Source Code Form is subject to the terms of the Mozilla Public 21 | * License, v. 2.0. If a copy of the MPL was not distributed with this 22 | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 23 | "use strict"; 24 | 25 | if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) { 26 | const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received."; 27 | const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; // Wrapping the bulk of this polyfill in a one-time-use function is a minor 28 | // optimization for Firefox. Since Spidermonkey does not fully parse the 29 | // contents of a function until the first time it's called, and since it will 30 | // never actually need to be called, this allows the polyfill to be included 31 | // in Firefox nearly for free. 32 | 33 | const wrapAPIs = extensionAPIs => { 34 | // NOTE: apiMetadata is associated to the content of the api-metadata.json file 35 | // at build time by replacing the following "include" with the content of the 36 | // JSON file. 37 | const apiMetadata = { 38 | "alarms": { 39 | "clear": { 40 | "minArgs": 0, 41 | "maxArgs": 1 42 | }, 43 | "clearAll": { 44 | "minArgs": 0, 45 | "maxArgs": 0 46 | }, 47 | "get": { 48 | "minArgs": 0, 49 | "maxArgs": 1 50 | }, 51 | "getAll": { 52 | "minArgs": 0, 53 | "maxArgs": 0 54 | } 55 | }, 56 | "bookmarks": { 57 | "create": { 58 | "minArgs": 1, 59 | "maxArgs": 1 60 | }, 61 | "get": { 62 | "minArgs": 1, 63 | "maxArgs": 1 64 | }, 65 | "getChildren": { 66 | "minArgs": 1, 67 | "maxArgs": 1 68 | }, 69 | "getRecent": { 70 | "minArgs": 1, 71 | "maxArgs": 1 72 | }, 73 | "getSubTree": { 74 | "minArgs": 1, 75 | "maxArgs": 1 76 | }, 77 | "getTree": { 78 | "minArgs": 0, 79 | "maxArgs": 0 80 | }, 81 | "move": { 82 | "minArgs": 2, 83 | "maxArgs": 2 84 | }, 85 | "remove": { 86 | "minArgs": 1, 87 | "maxArgs": 1 88 | }, 89 | "removeTree": { 90 | "minArgs": 1, 91 | "maxArgs": 1 92 | }, 93 | "search": { 94 | "minArgs": 1, 95 | "maxArgs": 1 96 | }, 97 | "update": { 98 | "minArgs": 2, 99 | "maxArgs": 2 100 | } 101 | }, 102 | "browserAction": { 103 | "disable": { 104 | "minArgs": 0, 105 | "maxArgs": 1, 106 | "fallbackToNoCallback": true 107 | }, 108 | "enable": { 109 | "minArgs": 0, 110 | "maxArgs": 1, 111 | "fallbackToNoCallback": true 112 | }, 113 | "getBadgeBackgroundColor": { 114 | "minArgs": 1, 115 | "maxArgs": 1 116 | }, 117 | "getBadgeText": { 118 | "minArgs": 1, 119 | "maxArgs": 1 120 | }, 121 | "getPopup": { 122 | "minArgs": 1, 123 | "maxArgs": 1 124 | }, 125 | "getTitle": { 126 | "minArgs": 1, 127 | "maxArgs": 1 128 | }, 129 | "openPopup": { 130 | "minArgs": 0, 131 | "maxArgs": 0 132 | }, 133 | "setBadgeBackgroundColor": { 134 | "minArgs": 1, 135 | "maxArgs": 1, 136 | "fallbackToNoCallback": true 137 | }, 138 | "setBadgeText": { 139 | "minArgs": 1, 140 | "maxArgs": 1, 141 | "fallbackToNoCallback": true 142 | }, 143 | "setIcon": { 144 | "minArgs": 1, 145 | "maxArgs": 1 146 | }, 147 | "setPopup": { 148 | "minArgs": 1, 149 | "maxArgs": 1, 150 | "fallbackToNoCallback": true 151 | }, 152 | "setTitle": { 153 | "minArgs": 1, 154 | "maxArgs": 1, 155 | "fallbackToNoCallback": true 156 | } 157 | }, 158 | "browsingData": { 159 | "remove": { 160 | "minArgs": 2, 161 | "maxArgs": 2 162 | }, 163 | "removeCache": { 164 | "minArgs": 1, 165 | "maxArgs": 1 166 | }, 167 | "removeCookies": { 168 | "minArgs": 1, 169 | "maxArgs": 1 170 | }, 171 | "removeDownloads": { 172 | "minArgs": 1, 173 | "maxArgs": 1 174 | }, 175 | "removeFormData": { 176 | "minArgs": 1, 177 | "maxArgs": 1 178 | }, 179 | "removeHistory": { 180 | "minArgs": 1, 181 | "maxArgs": 1 182 | }, 183 | "removeLocalStorage": { 184 | "minArgs": 1, 185 | "maxArgs": 1 186 | }, 187 | "removePasswords": { 188 | "minArgs": 1, 189 | "maxArgs": 1 190 | }, 191 | "removePluginData": { 192 | "minArgs": 1, 193 | "maxArgs": 1 194 | }, 195 | "settings": { 196 | "minArgs": 0, 197 | "maxArgs": 0 198 | } 199 | }, 200 | "commands": { 201 | "getAll": { 202 | "minArgs": 0, 203 | "maxArgs": 0 204 | } 205 | }, 206 | "contextMenus": { 207 | "remove": { 208 | "minArgs": 1, 209 | "maxArgs": 1 210 | }, 211 | "removeAll": { 212 | "minArgs": 0, 213 | "maxArgs": 0 214 | }, 215 | "update": { 216 | "minArgs": 2, 217 | "maxArgs": 2 218 | } 219 | }, 220 | "cookies": { 221 | "get": { 222 | "minArgs": 1, 223 | "maxArgs": 1 224 | }, 225 | "getAll": { 226 | "minArgs": 1, 227 | "maxArgs": 1 228 | }, 229 | "getAllCookieStores": { 230 | "minArgs": 0, 231 | "maxArgs": 0 232 | }, 233 | "remove": { 234 | "minArgs": 1, 235 | "maxArgs": 1 236 | }, 237 | "set": { 238 | "minArgs": 1, 239 | "maxArgs": 1 240 | } 241 | }, 242 | "devtools": { 243 | "inspectedWindow": { 244 | "eval": { 245 | "minArgs": 1, 246 | "maxArgs": 2, 247 | "singleCallbackArg": false 248 | } 249 | }, 250 | "panels": { 251 | "create": { 252 | "minArgs": 3, 253 | "maxArgs": 3, 254 | "singleCallbackArg": true 255 | } 256 | } 257 | }, 258 | "downloads": { 259 | "cancel": { 260 | "minArgs": 1, 261 | "maxArgs": 1 262 | }, 263 | "download": { 264 | "minArgs": 1, 265 | "maxArgs": 1 266 | }, 267 | "erase": { 268 | "minArgs": 1, 269 | "maxArgs": 1 270 | }, 271 | "getFileIcon": { 272 | "minArgs": 1, 273 | "maxArgs": 2 274 | }, 275 | "open": { 276 | "minArgs": 1, 277 | "maxArgs": 1, 278 | "fallbackToNoCallback": true 279 | }, 280 | "pause": { 281 | "minArgs": 1, 282 | "maxArgs": 1 283 | }, 284 | "removeFile": { 285 | "minArgs": 1, 286 | "maxArgs": 1 287 | }, 288 | "resume": { 289 | "minArgs": 1, 290 | "maxArgs": 1 291 | }, 292 | "search": { 293 | "minArgs": 1, 294 | "maxArgs": 1 295 | }, 296 | "show": { 297 | "minArgs": 1, 298 | "maxArgs": 1, 299 | "fallbackToNoCallback": true 300 | } 301 | }, 302 | "extension": { 303 | "isAllowedFileSchemeAccess": { 304 | "minArgs": 0, 305 | "maxArgs": 0 306 | }, 307 | "isAllowedIncognitoAccess": { 308 | "minArgs": 0, 309 | "maxArgs": 0 310 | } 311 | }, 312 | "history": { 313 | "addUrl": { 314 | "minArgs": 1, 315 | "maxArgs": 1 316 | }, 317 | "deleteAll": { 318 | "minArgs": 0, 319 | "maxArgs": 0 320 | }, 321 | "deleteRange": { 322 | "minArgs": 1, 323 | "maxArgs": 1 324 | }, 325 | "deleteUrl": { 326 | "minArgs": 1, 327 | "maxArgs": 1 328 | }, 329 | "getVisits": { 330 | "minArgs": 1, 331 | "maxArgs": 1 332 | }, 333 | "search": { 334 | "minArgs": 1, 335 | "maxArgs": 1 336 | } 337 | }, 338 | "i18n": { 339 | "detectLanguage": { 340 | "minArgs": 1, 341 | "maxArgs": 1 342 | }, 343 | "getAcceptLanguages": { 344 | "minArgs": 0, 345 | "maxArgs": 0 346 | } 347 | }, 348 | "identity": { 349 | "launchWebAuthFlow": { 350 | "minArgs": 1, 351 | "maxArgs": 1 352 | } 353 | }, 354 | "idle": { 355 | "queryState": { 356 | "minArgs": 1, 357 | "maxArgs": 1 358 | } 359 | }, 360 | "management": { 361 | "get": { 362 | "minArgs": 1, 363 | "maxArgs": 1 364 | }, 365 | "getAll": { 366 | "minArgs": 0, 367 | "maxArgs": 0 368 | }, 369 | "getSelf": { 370 | "minArgs": 0, 371 | "maxArgs": 0 372 | }, 373 | "setEnabled": { 374 | "minArgs": 2, 375 | "maxArgs": 2 376 | }, 377 | "uninstallSelf": { 378 | "minArgs": 0, 379 | "maxArgs": 1 380 | } 381 | }, 382 | "notifications": { 383 | "clear": { 384 | "minArgs": 1, 385 | "maxArgs": 1 386 | }, 387 | "create": { 388 | "minArgs": 1, 389 | "maxArgs": 2 390 | }, 391 | "getAll": { 392 | "minArgs": 0, 393 | "maxArgs": 0 394 | }, 395 | "getPermissionLevel": { 396 | "minArgs": 0, 397 | "maxArgs": 0 398 | }, 399 | "update": { 400 | "minArgs": 2, 401 | "maxArgs": 2 402 | } 403 | }, 404 | "pageAction": { 405 | "getPopup": { 406 | "minArgs": 1, 407 | "maxArgs": 1 408 | }, 409 | "getTitle": { 410 | "minArgs": 1, 411 | "maxArgs": 1 412 | }, 413 | "hide": { 414 | "minArgs": 1, 415 | "maxArgs": 1, 416 | "fallbackToNoCallback": true 417 | }, 418 | "setIcon": { 419 | "minArgs": 1, 420 | "maxArgs": 1 421 | }, 422 | "setPopup": { 423 | "minArgs": 1, 424 | "maxArgs": 1, 425 | "fallbackToNoCallback": true 426 | }, 427 | "setTitle": { 428 | "minArgs": 1, 429 | "maxArgs": 1, 430 | "fallbackToNoCallback": true 431 | }, 432 | "show": { 433 | "minArgs": 1, 434 | "maxArgs": 1, 435 | "fallbackToNoCallback": true 436 | } 437 | }, 438 | "permissions": { 439 | "contains": { 440 | "minArgs": 1, 441 | "maxArgs": 1 442 | }, 443 | "getAll": { 444 | "minArgs": 0, 445 | "maxArgs": 0 446 | }, 447 | "remove": { 448 | "minArgs": 1, 449 | "maxArgs": 1 450 | }, 451 | "request": { 452 | "minArgs": 1, 453 | "maxArgs": 1 454 | } 455 | }, 456 | "runtime": { 457 | "getBackgroundPage": { 458 | "minArgs": 0, 459 | "maxArgs": 0 460 | }, 461 | "getPlatformInfo": { 462 | "minArgs": 0, 463 | "maxArgs": 0 464 | }, 465 | "openOptionsPage": { 466 | "minArgs": 0, 467 | "maxArgs": 0 468 | }, 469 | "requestUpdateCheck": { 470 | "minArgs": 0, 471 | "maxArgs": 0 472 | }, 473 | "sendMessage": { 474 | "minArgs": 1, 475 | "maxArgs": 3 476 | }, 477 | "sendNativeMessage": { 478 | "minArgs": 2, 479 | "maxArgs": 2 480 | }, 481 | "setUninstallURL": { 482 | "minArgs": 1, 483 | "maxArgs": 1 484 | } 485 | }, 486 | "sessions": { 487 | "getDevices": { 488 | "minArgs": 0, 489 | "maxArgs": 1 490 | }, 491 | "getRecentlyClosed": { 492 | "minArgs": 0, 493 | "maxArgs": 1 494 | }, 495 | "restore": { 496 | "minArgs": 0, 497 | "maxArgs": 1 498 | } 499 | }, 500 | "storage": { 501 | "local": { 502 | "clear": { 503 | "minArgs": 0, 504 | "maxArgs": 0 505 | }, 506 | "get": { 507 | "minArgs": 0, 508 | "maxArgs": 1 509 | }, 510 | "getBytesInUse": { 511 | "minArgs": 0, 512 | "maxArgs": 1 513 | }, 514 | "remove": { 515 | "minArgs": 1, 516 | "maxArgs": 1 517 | }, 518 | "set": { 519 | "minArgs": 1, 520 | "maxArgs": 1 521 | } 522 | }, 523 | "managed": { 524 | "get": { 525 | "minArgs": 0, 526 | "maxArgs": 1 527 | }, 528 | "getBytesInUse": { 529 | "minArgs": 0, 530 | "maxArgs": 1 531 | } 532 | }, 533 | "sync": { 534 | "clear": { 535 | "minArgs": 0, 536 | "maxArgs": 0 537 | }, 538 | "get": { 539 | "minArgs": 0, 540 | "maxArgs": 1 541 | }, 542 | "getBytesInUse": { 543 | "minArgs": 0, 544 | "maxArgs": 1 545 | }, 546 | "remove": { 547 | "minArgs": 1, 548 | "maxArgs": 1 549 | }, 550 | "set": { 551 | "minArgs": 1, 552 | "maxArgs": 1 553 | } 554 | } 555 | }, 556 | "tabs": { 557 | "captureVisibleTab": { 558 | "minArgs": 0, 559 | "maxArgs": 2 560 | }, 561 | "create": { 562 | "minArgs": 1, 563 | "maxArgs": 1 564 | }, 565 | "detectLanguage": { 566 | "minArgs": 0, 567 | "maxArgs": 1 568 | }, 569 | "discard": { 570 | "minArgs": 0, 571 | "maxArgs": 1 572 | }, 573 | "duplicate": { 574 | "minArgs": 1, 575 | "maxArgs": 1 576 | }, 577 | "executeScript": { 578 | "minArgs": 1, 579 | "maxArgs": 2 580 | }, 581 | "get": { 582 | "minArgs": 1, 583 | "maxArgs": 1 584 | }, 585 | "getCurrent": { 586 | "minArgs": 0, 587 | "maxArgs": 0 588 | }, 589 | "getZoom": { 590 | "minArgs": 0, 591 | "maxArgs": 1 592 | }, 593 | "getZoomSettings": { 594 | "minArgs": 0, 595 | "maxArgs": 1 596 | }, 597 | "highlight": { 598 | "minArgs": 1, 599 | "maxArgs": 1 600 | }, 601 | "insertCSS": { 602 | "minArgs": 1, 603 | "maxArgs": 2 604 | }, 605 | "move": { 606 | "minArgs": 2, 607 | "maxArgs": 2 608 | }, 609 | "query": { 610 | "minArgs": 1, 611 | "maxArgs": 1 612 | }, 613 | "reload": { 614 | "minArgs": 0, 615 | "maxArgs": 2 616 | }, 617 | "remove": { 618 | "minArgs": 1, 619 | "maxArgs": 1 620 | }, 621 | "removeCSS": { 622 | "minArgs": 1, 623 | "maxArgs": 2 624 | }, 625 | "sendMessage": { 626 | "minArgs": 2, 627 | "maxArgs": 3 628 | }, 629 | "setZoom": { 630 | "minArgs": 1, 631 | "maxArgs": 2 632 | }, 633 | "setZoomSettings": { 634 | "minArgs": 1, 635 | "maxArgs": 2 636 | }, 637 | "update": { 638 | "minArgs": 1, 639 | "maxArgs": 2 640 | } 641 | }, 642 | "topSites": { 643 | "get": { 644 | "minArgs": 0, 645 | "maxArgs": 0 646 | } 647 | }, 648 | "webNavigation": { 649 | "getAllFrames": { 650 | "minArgs": 1, 651 | "maxArgs": 1 652 | }, 653 | "getFrame": { 654 | "minArgs": 1, 655 | "maxArgs": 1 656 | } 657 | }, 658 | "webRequest": { 659 | "handlerBehaviorChanged": { 660 | "minArgs": 0, 661 | "maxArgs": 0 662 | } 663 | }, 664 | "windows": { 665 | "create": { 666 | "minArgs": 0, 667 | "maxArgs": 1 668 | }, 669 | "get": { 670 | "minArgs": 1, 671 | "maxArgs": 2 672 | }, 673 | "getAll": { 674 | "minArgs": 0, 675 | "maxArgs": 1 676 | }, 677 | "getCurrent": { 678 | "minArgs": 0, 679 | "maxArgs": 1 680 | }, 681 | "getLastFocused": { 682 | "minArgs": 0, 683 | "maxArgs": 1 684 | }, 685 | "remove": { 686 | "minArgs": 1, 687 | "maxArgs": 1 688 | }, 689 | "update": { 690 | "minArgs": 2, 691 | "maxArgs": 2 692 | } 693 | } 694 | }; 695 | 696 | if (Object.keys(apiMetadata).length === 0) { 697 | throw new Error("api-metadata.json has not been included in browser-polyfill"); 698 | } 699 | /** 700 | * A WeakMap subclass which creates and stores a value for any key which does 701 | * not exist when accessed, but behaves exactly as an ordinary WeakMap 702 | * otherwise. 703 | * 704 | * @param {function} createItem 705 | * A function which will be called in order to create the value for any 706 | * key which does not exist, the first time it is accessed. The 707 | * function receives, as its only argument, the key being created. 708 | */ 709 | 710 | 711 | class DefaultWeakMap extends WeakMap { 712 | constructor(createItem, items = undefined) { 713 | super(items); 714 | this.createItem = createItem; 715 | } 716 | 717 | get(key) { 718 | if (!this.has(key)) { 719 | this.set(key, this.createItem(key)); 720 | } 721 | 722 | return super.get(key); 723 | } 724 | 725 | } 726 | /** 727 | * Returns true if the given object is an object with a `then` method, and can 728 | * therefore be assumed to behave as a Promise. 729 | * 730 | * @param {*} value The value to test. 731 | * @returns {boolean} True if the value is thenable. 732 | */ 733 | 734 | 735 | const isThenable = value => { 736 | return value && typeof value === "object" && typeof value.then === "function"; 737 | }; 738 | /** 739 | * Creates and returns a function which, when called, will resolve or reject 740 | * the given promise based on how it is called: 741 | * 742 | * - If, when called, `chrome.runtime.lastError` contains a non-null object, 743 | * the promise is rejected with that value. 744 | * - If the function is called with exactly one argument, the promise is 745 | * resolved to that value. 746 | * - Otherwise, the promise is resolved to an array containing all of the 747 | * function's arguments. 748 | * 749 | * @param {object} promise 750 | * An object containing the resolution and rejection functions of a 751 | * promise. 752 | * @param {function} promise.resolve 753 | * The promise's resolution function. 754 | * @param {function} promise.rejection 755 | * The promise's rejection function. 756 | * @param {object} metadata 757 | * Metadata about the wrapped method which has created the callback. 758 | * @param {integer} metadata.maxResolvedArgs 759 | * The maximum number of arguments which may be passed to the 760 | * callback created by the wrapped async function. 761 | * 762 | * @returns {function} 763 | * The generated callback function. 764 | */ 765 | 766 | 767 | const makeCallback = (promise, metadata) => { 768 | return (...callbackArgs) => { 769 | if (extensionAPIs.runtime.lastError) { 770 | promise.reject(extensionAPIs.runtime.lastError); 771 | } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) { 772 | promise.resolve(callbackArgs[0]); 773 | } else { 774 | promise.resolve(callbackArgs); 775 | } 776 | }; 777 | }; 778 | 779 | const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments"; 780 | /** 781 | * Creates a wrapper function for a method with the given name and metadata. 782 | * 783 | * @param {string} name 784 | * The name of the method which is being wrapped. 785 | * @param {object} metadata 786 | * Metadata about the method being wrapped. 787 | * @param {integer} metadata.minArgs 788 | * The minimum number of arguments which must be passed to the 789 | * function. If called with fewer than this number of arguments, the 790 | * wrapper will raise an exception. 791 | * @param {integer} metadata.maxArgs 792 | * The maximum number of arguments which may be passed to the 793 | * function. If called with more than this number of arguments, the 794 | * wrapper will raise an exception. 795 | * @param {integer} metadata.maxResolvedArgs 796 | * The maximum number of arguments which may be passed to the 797 | * callback created by the wrapped async function. 798 | * 799 | * @returns {function(object, ...*)} 800 | * The generated wrapper function. 801 | */ 802 | 803 | 804 | const wrapAsyncFunction = (name, metadata) => { 805 | return function asyncFunctionWrapper(target, ...args) { 806 | if (args.length < metadata.minArgs) { 807 | throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); 808 | } 809 | 810 | if (args.length > metadata.maxArgs) { 811 | throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); 812 | } 813 | 814 | return new Promise((resolve, reject) => { 815 | if (metadata.fallbackToNoCallback) { 816 | // This API method has currently no callback on Chrome, but it return a promise on Firefox, 817 | // and so the polyfill will try to call it with a callback first, and it will fallback 818 | // to not passing the callback if the first call fails. 819 | try { 820 | target[name](...args, makeCallback({ 821 | resolve, 822 | reject 823 | }, metadata)); 824 | } catch (cbError) { 825 | console.warn(`${name} API method doesn't seem to support the callback parameter, ` + "falling back to call it without a callback: ", cbError); 826 | target[name](...args); // Update the API method metadata, so that the next API calls will not try to 827 | // use the unsupported callback anymore. 828 | 829 | metadata.fallbackToNoCallback = false; 830 | metadata.noCallback = true; 831 | resolve(); 832 | } 833 | } else if (metadata.noCallback) { 834 | target[name](...args); 835 | resolve(); 836 | } else { 837 | target[name](...args, makeCallback({ 838 | resolve, 839 | reject 840 | }, metadata)); 841 | } 842 | }); 843 | }; 844 | }; 845 | /** 846 | * Wraps an existing method of the target object, so that calls to it are 847 | * intercepted by the given wrapper function. The wrapper function receives, 848 | * as its first argument, the original `target` object, followed by each of 849 | * the arguments passed to the original method. 850 | * 851 | * @param {object} target 852 | * The original target object that the wrapped method belongs to. 853 | * @param {function} method 854 | * The method being wrapped. This is used as the target of the Proxy 855 | * object which is created to wrap the method. 856 | * @param {function} wrapper 857 | * The wrapper function which is called in place of a direct invocation 858 | * of the wrapped method. 859 | * 860 | * @returns {Proxy} 861 | * A Proxy object for the given method, which invokes the given wrapper 862 | * method in its place. 863 | */ 864 | 865 | 866 | const wrapMethod = (target, method, wrapper) => { 867 | return new Proxy(method, { 868 | apply(targetMethod, thisObj, args) { 869 | return wrapper.call(thisObj, target, ...args); 870 | } 871 | 872 | }); 873 | }; 874 | 875 | let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); 876 | /** 877 | * Wraps an object in a Proxy which intercepts and wraps certain methods 878 | * based on the given `wrappers` and `metadata` objects. 879 | * 880 | * @param {object} target 881 | * The target object to wrap. 882 | * 883 | * @param {object} [wrappers = {}] 884 | * An object tree containing wrapper functions for special cases. Any 885 | * function present in this object tree is called in place of the 886 | * method in the same location in the `target` object tree. These 887 | * wrapper methods are invoked as described in {@see wrapMethod}. 888 | * 889 | * @param {object} [metadata = {}] 890 | * An object tree containing metadata used to automatically generate 891 | * Promise-based wrapper functions for asynchronous. Any function in 892 | * the `target` object tree which has a corresponding metadata object 893 | * in the same location in the `metadata` tree is replaced with an 894 | * automatically-generated wrapper function, as described in 895 | * {@see wrapAsyncFunction} 896 | * 897 | * @returns {Proxy} 898 | */ 899 | 900 | const wrapObject = (target, wrappers = {}, metadata = {}) => { 901 | let cache = Object.create(null); 902 | let handlers = { 903 | has(proxyTarget, prop) { 904 | return prop in target || prop in cache; 905 | }, 906 | 907 | get(proxyTarget, prop, receiver) { 908 | if (prop in cache) { 909 | return cache[prop]; 910 | } 911 | 912 | if (!(prop in target)) { 913 | return undefined; 914 | } 915 | 916 | let value = target[prop]; 917 | 918 | if (typeof value === "function") { 919 | // This is a method on the underlying object. Check if we need to do 920 | // any wrapping. 921 | if (typeof wrappers[prop] === "function") { 922 | // We have a special-case wrapper for this method. 923 | value = wrapMethod(target, target[prop], wrappers[prop]); 924 | } else if (hasOwnProperty(metadata, prop)) { 925 | // This is an async method that we have metadata for. Create a 926 | // Promise wrapper for it. 927 | let wrapper = wrapAsyncFunction(prop, metadata[prop]); 928 | value = wrapMethod(target, target[prop], wrapper); 929 | } else { 930 | // This is a method that we don't know or care about. Return the 931 | // original method, bound to the underlying object. 932 | value = value.bind(target); 933 | } 934 | } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) { 935 | // This is an object that we need to do some wrapping for the children 936 | // of. Create a sub-object wrapper for it with the appropriate child 937 | // metadata. 938 | value = wrapObject(value, wrappers[prop], metadata[prop]); 939 | } else if (hasOwnProperty(metadata, "*")) { 940 | // Wrap all properties in * namespace. 941 | value = wrapObject(value, wrappers[prop], metadata["*"]); 942 | } else { 943 | // We don't need to do any wrapping for this property, 944 | // so just forward all access to the underlying object. 945 | Object.defineProperty(cache, prop, { 946 | configurable: true, 947 | enumerable: true, 948 | 949 | get() { 950 | return target[prop]; 951 | }, 952 | 953 | set(value) { 954 | target[prop] = value; 955 | } 956 | 957 | }); 958 | return value; 959 | } 960 | 961 | cache[prop] = value; 962 | return value; 963 | }, 964 | 965 | set(proxyTarget, prop, value, receiver) { 966 | if (prop in cache) { 967 | cache[prop] = value; 968 | } else { 969 | target[prop] = value; 970 | } 971 | 972 | return true; 973 | }, 974 | 975 | defineProperty(proxyTarget, prop, desc) { 976 | return Reflect.defineProperty(cache, prop, desc); 977 | }, 978 | 979 | deleteProperty(proxyTarget, prop) { 980 | return Reflect.deleteProperty(cache, prop); 981 | } 982 | 983 | }; // Per contract of the Proxy API, the "get" proxy handler must return the 984 | // original value of the target if that value is declared read-only and 985 | // non-configurable. For this reason, we create an object with the 986 | // prototype set to `target` instead of using `target` directly. 987 | // Otherwise we cannot return a custom object for APIs that 988 | // are declared read-only and non-configurable, such as `chrome.devtools`. 989 | // 990 | // The proxy handlers themselves will still use the original `target` 991 | // instead of the `proxyTarget`, so that the methods and properties are 992 | // dereferenced via the original targets. 993 | 994 | let proxyTarget = Object.create(target); 995 | return new Proxy(proxyTarget, handlers); 996 | }; 997 | /** 998 | * Creates a set of wrapper functions for an event object, which handles 999 | * wrapping of listener functions that those messages are passed. 1000 | * 1001 | * A single wrapper is created for each listener function, and stored in a 1002 | * map. Subsequent calls to `addListener`, `hasListener`, or `removeListener` 1003 | * retrieve the original wrapper, so that attempts to remove a 1004 | * previously-added listener work as expected. 1005 | * 1006 | * @param {DefaultWeakMap} wrapperMap 1007 | * A DefaultWeakMap object which will create the appropriate wrapper 1008 | * for a given listener function when one does not exist, and retrieve 1009 | * an existing one when it does. 1010 | * 1011 | * @returns {object} 1012 | */ 1013 | 1014 | 1015 | const wrapEvent = wrapperMap => ({ 1016 | addListener(target, listener, ...args) { 1017 | target.addListener(wrapperMap.get(listener), ...args); 1018 | }, 1019 | 1020 | hasListener(target, listener) { 1021 | return target.hasListener(wrapperMap.get(listener)); 1022 | }, 1023 | 1024 | removeListener(target, listener) { 1025 | target.removeListener(wrapperMap.get(listener)); 1026 | } 1027 | 1028 | }); // Keep track if the deprecation warning has been logged at least once. 1029 | 1030 | 1031 | let loggedSendResponseDeprecationWarning = false; 1032 | const onMessageWrappers = new DefaultWeakMap(listener => { 1033 | if (typeof listener !== "function") { 1034 | return listener; 1035 | } 1036 | /** 1037 | * Wraps a message listener function so that it may send responses based on 1038 | * its return value, rather than by returning a sentinel value and calling a 1039 | * callback. If the listener function returns a Promise, the response is 1040 | * sent when the promise either resolves or rejects. 1041 | * 1042 | * @param {*} message 1043 | * The message sent by the other end of the channel. 1044 | * @param {object} sender 1045 | * Details about the sender of the message. 1046 | * @param {function(*)} sendResponse 1047 | * A callback which, when called with an arbitrary argument, sends 1048 | * that value as a response. 1049 | * @returns {boolean} 1050 | * True if the wrapped listener returned a Promise, which will later 1051 | * yield a response. False otherwise. 1052 | */ 1053 | 1054 | 1055 | return function onMessage(message, sender, sendResponse) { 1056 | let didCallSendResponse = false; 1057 | let wrappedSendResponse; 1058 | let sendResponsePromise = new Promise(resolve => { 1059 | wrappedSendResponse = function (response) { 1060 | if (!loggedSendResponseDeprecationWarning) { 1061 | console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack); 1062 | loggedSendResponseDeprecationWarning = true; 1063 | } 1064 | 1065 | didCallSendResponse = true; 1066 | resolve(response); 1067 | }; 1068 | }); 1069 | let result; 1070 | 1071 | try { 1072 | result = listener(message, sender, wrappedSendResponse); 1073 | } catch (err) { 1074 | result = Promise.reject(err); 1075 | } 1076 | 1077 | const isResultThenable = result !== true && isThenable(result); // If the listener didn't returned true or a Promise, or called 1078 | // wrappedSendResponse synchronously, we can exit earlier 1079 | // because there will be no response sent from this listener. 1080 | 1081 | if (result !== true && !isResultThenable && !didCallSendResponse) { 1082 | return false; 1083 | } // A small helper to send the message if the promise resolves 1084 | // and an error if the promise rejects (a wrapped sendMessage has 1085 | // to translate the message into a resolved promise or a rejected 1086 | // promise). 1087 | 1088 | 1089 | const sendPromisedResult = promise => { 1090 | promise.then(msg => { 1091 | // send the message value. 1092 | sendResponse(msg); 1093 | }, error => { 1094 | // Send a JSON representation of the error if the rejected value 1095 | // is an instance of error, or the object itself otherwise. 1096 | let message; 1097 | 1098 | if (error && (error instanceof Error || typeof error.message === "string")) { 1099 | message = error.message; 1100 | } else { 1101 | message = "An unexpected error occurred"; 1102 | } 1103 | 1104 | sendResponse({ 1105 | __mozWebExtensionPolyfillReject__: true, 1106 | message 1107 | }); 1108 | }).catch(err => { 1109 | // Print an error on the console if unable to send the response. 1110 | console.error("Failed to send onMessage rejected reply", err); 1111 | }); 1112 | }; // If the listener returned a Promise, send the resolved value as a 1113 | // result, otherwise wait the promise related to the wrappedSendResponse 1114 | // callback to resolve and send it as a response. 1115 | 1116 | 1117 | if (isResultThenable) { 1118 | sendPromisedResult(result); 1119 | } else { 1120 | sendPromisedResult(sendResponsePromise); 1121 | } // Let Chrome know that the listener is replying. 1122 | 1123 | 1124 | return true; 1125 | }; 1126 | }); 1127 | 1128 | const wrappedSendMessageCallback = ({ 1129 | reject, 1130 | resolve 1131 | }, reply) => { 1132 | if (extensionAPIs.runtime.lastError) { 1133 | // Detect when none of the listeners replied to the sendMessage call and resolve 1134 | // the promise to undefined as in Firefox. 1135 | // See https://github.com/mozilla/webextension-polyfill/issues/130 1136 | if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) { 1137 | resolve(); 1138 | } else { 1139 | reject(extensionAPIs.runtime.lastError); 1140 | } 1141 | } else if (reply && reply.__mozWebExtensionPolyfillReject__) { 1142 | // Convert back the JSON representation of the error into 1143 | // an Error instance. 1144 | reject(new Error(reply.message)); 1145 | } else { 1146 | resolve(reply); 1147 | } 1148 | }; 1149 | 1150 | const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => { 1151 | if (args.length < metadata.minArgs) { 1152 | throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); 1153 | } 1154 | 1155 | if (args.length > metadata.maxArgs) { 1156 | throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); 1157 | } 1158 | 1159 | return new Promise((resolve, reject) => { 1160 | const wrappedCb = wrappedSendMessageCallback.bind(null, { 1161 | resolve, 1162 | reject 1163 | }); 1164 | args.push(wrappedCb); 1165 | apiNamespaceObj.sendMessage(...args); 1166 | }); 1167 | }; 1168 | 1169 | const staticWrappers = { 1170 | runtime: { 1171 | onMessage: wrapEvent(onMessageWrappers), 1172 | onMessageExternal: wrapEvent(onMessageWrappers), 1173 | sendMessage: wrappedSendMessage.bind(null, "sendMessage", { 1174 | minArgs: 1, 1175 | maxArgs: 3 1176 | }) 1177 | }, 1178 | tabs: { 1179 | sendMessage: wrappedSendMessage.bind(null, "sendMessage", { 1180 | minArgs: 2, 1181 | maxArgs: 3 1182 | }) 1183 | } 1184 | }; 1185 | const settingMetadata = { 1186 | clear: { 1187 | minArgs: 1, 1188 | maxArgs: 1 1189 | }, 1190 | get: { 1191 | minArgs: 1, 1192 | maxArgs: 1 1193 | }, 1194 | set: { 1195 | minArgs: 1, 1196 | maxArgs: 1 1197 | } 1198 | }; 1199 | apiMetadata.privacy = { 1200 | network: { 1201 | "*": settingMetadata 1202 | }, 1203 | services: { 1204 | "*": settingMetadata 1205 | }, 1206 | websites: { 1207 | "*": settingMetadata 1208 | } 1209 | }; 1210 | return wrapObject(extensionAPIs, staticWrappers, apiMetadata); 1211 | }; 1212 | 1213 | if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) { 1214 | throw new Error("This script should only be loaded in a browser extension."); 1215 | } // The build process adds a UMD wrapper around this file, which makes the 1216 | // `module` variable available. 1217 | 1218 | 1219 | module.exports = wrapAPIs(chrome); 1220 | } else { 1221 | module.exports = browser; 1222 | } 1223 | }); 1224 | //# sourceMappingURL=browser-polyfill.js.map 1225 | --------------------------------------------------------------------------------