├── .editorconfig ├── .eslintignore ├── .eslintrc ├── LICENSE ├── README.md ├── _locales ├── en │ └── messages.json ├── ja │ └── messages.json └── ru │ └── messages.json ├── bg ├── bg-api.js ├── bg-filter.js ├── bg-icon.js ├── bg-launch.js ├── bg-offscreen.js ├── bg-settings.js ├── bg-switch.js ├── bg-trim.js ├── bg-unpack.js ├── bg-update.js ├── bg-util.js ├── bg.js ├── offscreen.html └── offscreen.js ├── content ├── fix-google.js ├── pager.js └── xpather.js ├── icons ├── 128.png ├── 16.png ├── 32.png ├── 48.png └── off │ ├── 16.png │ ├── 32.png │ └── 48.png ├── manifest.json ├── siteinfo-updater.js ├── siteinfo.json ├── ui ├── options-backup.js ├── options-dark.css ├── options-rules.js ├── options.css ├── options.html ├── options.js ├── popup-dark.css ├── popup-exclude.js ├── popup-fail-detect.js ├── popup-generic-rules.js ├── popup-load-more.js ├── popup.css ├── popup.html └── popup.js └── util ├── common.js ├── dom.js ├── locale.js ├── lz-string.js └── storage-idb.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | tab_width = 2 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | util/lz-string.js 2 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | # https://github.com/eslint/eslint/blob/master/docs/rules/README.md 2 | 3 | parserOptions: 4 | ecmaVersion: 2022 5 | sourceType: module 6 | 7 | env: 8 | browser: true 9 | es6: true 10 | webextensions: true 11 | 12 | rules: 13 | accessor-pairs: [2] 14 | array-bracket-spacing: [2, never] 15 | array-callback-return: [0] 16 | arrow-body-style: [2, as-needed] 17 | arrow-parens: [2, as-needed] 18 | arrow-spacing: [2, {before: true, after: true}] 19 | block-scoped-var: [2] 20 | brace-style: [2, 1tbs, {allowSingleLine: true}] 21 | camelcase: [2, {properties: never}] 22 | class-methods-use-this: [2] 23 | comma-dangle: [2, {arrays: always-multiline, objects: always-multiline, exports: always-multiline, imports: always-multiline}] 24 | comma-spacing: [2, {before: false, after: true}] 25 | comma-style: [2, last] 26 | complexity: [0] 27 | computed-property-spacing: [2, never] 28 | consistent-return: [0] 29 | constructor-super: [2] 30 | curly: [0, multi-or-nest] 31 | default-case: [0] 32 | dot-location: [2, property] 33 | dot-notation: [2] 34 | eol-last: [2] 35 | eqeqeq: [2, smart] 36 | func-call-spacing: [2, never] 37 | func-name-matching: [0] 38 | func-names: [0] 39 | generator-star-spacing: [2, before] 40 | global-require: [0] 41 | guard-for-in: [0] 42 | handle-callback-err: [2, ^(err|error)$] 43 | id-blacklist: [0] 44 | id-length: [0] 45 | id-match: [0] 46 | indent: [2, 2, {VariableDeclarator: 1, SwitchCase: 1, MemberExpression: off}] 47 | jsx-quotes: [0] 48 | key-spacing: [2, {mode: minimum}] 49 | keyword-spacing: [2] 50 | lines-around-comment: [0] 51 | lines-around-directive: [0] 52 | max-len: [2, { 53 | code: 100, 54 | ignoreComments: true, 55 | ignoreRegExpLiterals: true, 56 | ignoreTemplateLiterals: true, 57 | ignorePattern: "\\burl\\(\\s*[\"']?data:" 58 | }] 59 | max-lines: [0] 60 | max-nested-callbacks: [0] 61 | max-params: [0] 62 | max-statements-per-line: [0] 63 | max-statements: [0] 64 | multiline-ternary: [0, always-multiline] 65 | new-cap: [0] 66 | new-parens: [2] 67 | newline-before-return: [0] 68 | newline-per-chained-call: [0] 69 | no-alert: [0] 70 | no-array-constructor: [0] 71 | no-bitwise: [0] 72 | no-caller: [2] 73 | no-case-declarations: [2] 74 | no-class-assign: [2] 75 | no-cond-assign: [2, except-parens] 76 | no-confusing-arrow: [0, {allowParens: true}] 77 | no-const-assign: [2] 78 | no-constant-condition: [0] 79 | no-continue: [0] 80 | no-control-regex: [0] 81 | no-debugger: [2] 82 | no-delete-var: [2] 83 | no-div-regex: [0] 84 | no-dupe-args: [2] 85 | no-dupe-class-members: [2] 86 | no-dupe-keys: [2] 87 | no-duplicate-case: [2] 88 | no-duplicate-imports: [2] 89 | no-else-return: [0] 90 | no-empty-character-class: [2] 91 | no-empty-function: [0] 92 | no-empty-pattern: [2] 93 | no-empty: [2, {allowEmptyCatch: true}] 94 | no-eq-null: [0] 95 | no-eval: [2] 96 | no-ex-assign: [2] 97 | no-extend-native: [2] 98 | no-extra-bind: [2] 99 | no-extra-boolean-cast: [2] 100 | no-extra-label: [0] 101 | no-extra-parens: [0] 102 | no-extra-semi: [2] 103 | no-fallthrough: [2, {commentPattern: fallthrough.*}] 104 | no-floating-decimal: [0] 105 | no-func-assign: [2] 106 | no-global-assign: [2] 107 | no-implicit-coercion: [0] 108 | no-implicit-globals: [0] 109 | no-implied-eval: [2] 110 | no-inline-comments: [0] 111 | no-inner-declarations: [2] 112 | no-invalid-regexp: [2] 113 | no-invalid-this: [2] 114 | no-irregular-whitespace: [2] 115 | no-iterator: [2] 116 | no-label-var: [2] 117 | no-labels: [2, {allowLoop: true}] 118 | no-lone-blocks: [2] 119 | no-lonely-if: [0] 120 | no-loop-func: [2] 121 | no-magic-numbers: [0] 122 | no-mixed-operators: [0] 123 | no-mixed-requires: [2, true] 124 | no-mixed-spaces-and-tabs: [2] 125 | no-multi-spaces: [2, {ignoreEOLComments: true}] 126 | no-multi-str: [2] 127 | no-multiple-empty-lines: [2, {max: 2, maxEOF: 0, maxBOF: 0}] 128 | no-native-reassign: [2] 129 | no-negated-condition: [0] 130 | no-negated-in-lhs: [2] 131 | no-nested-ternary: [0] 132 | no-new-func: [2] 133 | no-new-object: [2] 134 | no-new-require: [2] 135 | no-new-symbol: [2] 136 | no-new-wrappers: [2] 137 | no-new: [0] 138 | no-obj-calls: [2] 139 | no-octal-escape: [2] 140 | no-octal: [2] 141 | no-path-concat: [2] 142 | no-process-exit: [0] 143 | no-proto: [2] 144 | no-redeclare: [2] 145 | no-regex-spaces: [2] 146 | no-restricted-imports: [0] 147 | no-restricted-modules: [2, domain, freelist, smalloc, sys] 148 | no-restricted-syntax: [2, WithStatement] 149 | no-return-assign: [2, except-parens] 150 | no-return-await: [2] 151 | no-script-url: [2] 152 | no-self-assign: [2, {props: true}] 153 | no-self-compare: [2] 154 | no-sequences: [0] 155 | no-shadow-restricted-names: [2] 156 | no-shadow: [0] 157 | no-spaced-func: [2] 158 | no-sparse-arrays: [2] 159 | no-tabs: [2] 160 | no-template-curly-in-string: [2] 161 | no-this-before-super: [2] 162 | no-throw-literal: [0] 163 | no-trailing-spaces: [2] 164 | no-undef-init: [2] 165 | no-undef: [2] 166 | no-undefined: [0] 167 | no-underscore-dangle: [0] 168 | no-unexpected-multiline: [2] 169 | no-unmodified-loop-condition: [0] 170 | no-unneeded-ternary: [2] 171 | no-unreachable: [2] 172 | no-unsafe-finally: [2] 173 | no-unsafe-negation: [2] 174 | no-unused-expressions: [1, {allowShortCircuit: true, allowTernary: true}] 175 | no-unused-labels: [0] 176 | no-unused-vars: [1, { 177 | args: after-used, 178 | vars: local, 179 | ignoreRestSiblings: true, 180 | argsIgnorePattern: ^_|^e$ 181 | }] 182 | no-use-before-define: [2, {functions: false, classes: false}] 183 | no-useless-call: [2] 184 | no-useless-computed-key: [2] 185 | no-useless-concat: [0] 186 | no-useless-constructor: [2] 187 | no-useless-escape: [2] 188 | no-var: [2] 189 | no-warning-comments: [0] 190 | no-whitespace-before-property: [2] 191 | no-with: [2] 192 | nonblock-statement-body-position: [0] 193 | object-curly-newline: [2, {multiline: true, consistent: true}] 194 | object-curly-spacing: [2, never] 195 | object-shorthand: [0] 196 | one-var-declaration-per-line: [1] 197 | one-var: [2, {initialized: never}] 198 | operator-assignment: [2, always] 199 | operator-linebreak: [2, after, overrides: {"?": ignore, ":": ignore, "&&": ignore, "||": ignore}] 200 | padded-blocks: [0] 201 | prefer-const: [1, {destructuring: all, ignoreReadBeforeAssign: true}] 202 | prefer-numeric-literals: [2] 203 | prefer-rest-params: [0] 204 | quote-props: [2, consistent] 205 | quotes: [1, single, avoid-escape] 206 | radix: [2, as-needed] 207 | require-jsdoc: [0] 208 | require-yield: [2] 209 | semi-spacing: [2, {before: false, after: true}] 210 | semi: [2, always] 211 | sort-imports: [0] 212 | sort-keys: [0] 213 | space-before-blocks: [2, always] 214 | space-before-function-paren: [2, {anonymous: always, asyncArrow: always, named: never}] 215 | space-in-parens: [2, never] 216 | space-infix-ops: [2] 217 | space-unary-ops: [2] 218 | spaced-comment: [0, always, {markers: ["!"]}] 219 | strict: [2, global] 220 | symbol-description: [2] 221 | template-curly-spacing: [2, never] 222 | unicode-bom: [2, never] 223 | use-isnan: [2] 224 | valid-typeof: [2] 225 | wrap-iife: [2, inside] 226 | yield-star-spacing: [2, {before: true, after: false}] 227 | yoda: [2, never] 228 | 229 | overrides: 230 | - files: 231 | - "content/*.js" 232 | parserOptions: 233 | sourceType: script 234 | globals: 235 | xpather: false 236 | run: false 237 | 238 | - files: 239 | - ui/popup-fail-detect.js 240 | parserOptions: 241 | sourceType: script 242 | 243 | - files: 244 | - "siteinfo-updater.js" 245 | parserOptions: 246 | sourceType: script 247 | env: 248 | node: true 249 | 250 | - files: 251 | - "bg/bg*" 252 | env: 253 | browser: false 254 | serviceworker: true 255 | globals: 256 | createImageBitmap: false 257 | OffscreenCanvas: false 258 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### A fork of [Autopagerize for Chrome](https://github.com/swdyh/autopagerize_for_chrome) 2 | 3 | 4 | 5 | Fully reworked to reduce memory consumption and increase performance: 6 | 7 | * inactivity timeout of the background script is configurable, so you can choose a shorter timeout to conserve memory (~30MB) or a longer timeout to conserve CPU due to a faster checking of URL regexps (from half a second right after start to just a few milliseconds in subsequent checks). 8 | * visited URL's rules are cached in IndexedDB to avoid re-checking thousands of rules 9 | * simple URL regexps are converted to the much faster literal string checks 10 | * the data is stored in IndexedDB 11 | * the content script is added to a web page only if its URL has a matching rule 12 | * the content script unregisters all of its listeners to free up memory, when there are no more pages to load or the extension is toggled off in the popup or via a hotkey 13 | * simple one-time messaging is used to avoid persisting the ports for all tabs 14 | 15 | ### Differences to the original: 16 | 17 | * Generic rules are disabled by default and can be re-enabled per site/pattern (a `*` pattern that matches all sites may be used to restore the old behavior) in the options or the popup. This is because these rules (currently there are three) seem to be useless as the popular sites all have a custom rule, while breaking the page layout on less popular sites a bit too often. 18 | * Exclusions are matched to the full URL now unless there's a `*` at the end. The original extension has been incorrectly treating all non-regexp URLs as prefixes. 19 | * `http://foo.com/bar` - this exact URL 20 | * `http://foo.com/bar*` - URLs that start with `http://foo.com/bar` 21 | * `*.foo.com/bar` - URLs that end in `foo.com/bar` 22 | * `*://*.foo.com/bar*` - URLs that contain `foo.com/bar` anywhere 23 | 24 | ### New features: 25 | 26 | * Configurable hotkeys chrome://extensions/shortcuts: 27 | * On/Off switch 28 | * Show the popup 29 | * Load 1,2,5,10 more pages - four separate commands 30 | * On/Off command in the context menu of the extension icon in the browser toolbar 31 | 32 | ![popup](https://i.imgur.com/8tqVUxs.png) ![popup-dark](https://i.imgur.com/aV2cyw8.png) 33 | 34 | ### New features in popup: 35 | 36 | * Load 1-100 more pages 37 | * Exclude current page URL/prefix/domain 38 | * Enable generic rules for current page URL/prefix/domain 39 | 40 | ### New options: 41 | 42 | * Custom rules 43 | * Ability to start the database update manually 44 | * Customizable internal parameters 45 | * Import/export 46 | 47 | ### New DOM event: `GM_AutoPagerizeNextPageDoc` 48 | 49 | Fired after downloading the new page so that other scripts may alter it like this: 50 | ```js 51 | document.addEventListener('GM_AutoPagerizeNextPageDoc', e => { 52 | const doc = e.relatedTarget; 53 | const url = doc.URL; 54 | for (const el of doc.querySelectorAll('img[alt][title]')) { 55 | el.loading = 'lazy'; 56 | } 57 | }); 58 | ``` 59 | 60 | ![options-dark](https://i.imgur.com/4GNQkYw.png) 61 | 62 | ### Permissions: 63 | 64 | * `wedata.net` - used to update the database of pagination rules from http://wedata.net/databases/AutoPagerize/items_all.json which is stripped of everything except XPath selectors for the page elements and RegExp for the page URL 65 | * `` - required to paginate while you browse according to the database of rules (technically, to find the "next page" and "page body" elements) 66 | * `alarms` - to schedule a database update 67 | * `contextMenus` - to add an "On/off" item to the context menu of the extension icon in the browser toolbar 68 | * `offscreen` - ManifestV3 way of handling DOM/XHR in the background script 69 | * `scripting` - to run the pagination script in the matching tabs 70 | * `storage` - to store the options of the extension 71 | * `tabs` - most notably to restart the paging functionality on extension update, also to notify the tabs that match the URL that you've just manually excluded in the popup 72 | * `webNavigation` - to schedule a pagination check when you navigate to a new URL 73 | 74 | ### How to limit the site permissions 75 | 76 | Chrome allows you to easily limit the extension so it can access only a few sites: 77 | 78 | 1. right-click the extension icon in the toolbar (or browser menu) and click "Manage" - it'll open `chrome://extensions` details page for this extension 79 | 2. click "On specific sites" 80 | 3. enter the URL you want to allow 81 | 4. to add more sites click "Add a new page" 82 | 5. add `http://wedata.net` to keep the database of rules up-to-date. 83 | 84 | ![limit UI](https://i.imgur.com/F2nqVdL.png) 85 | -------------------------------------------------------------------------------- /_locales/en/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "add": { 3 | "message": "Add" 4 | }, 5 | "customRules": { 6 | "message": "Custom rules" 7 | }, 8 | "description": { 9 | "message": "Infiniscroll on web pages using a large database of rules" 10 | }, 11 | "showStatus": { 12 | "message": "Show status while loading" 13 | }, 14 | "darkTheme": { 15 | "message": "Dark theme in popup/options" 16 | }, 17 | "date": { 18 | "message": "Date" 19 | }, 20 | "delete": { 21 | "message": "Delete" 22 | }, 23 | "done": { 24 | "message": "Done" 25 | }, 26 | "error": { 27 | "message": "Error" 28 | }, 29 | "errorEmptyValue": { 30 | "message": "Empty value is not valid" 31 | }, 32 | "errorExtractInfo": { 33 | "message": "cannot extract the next page element or URL" 34 | }, 35 | "errorOrigin": { 36 | "message": "next link URL is not within the page domain" 37 | }, 38 | "example": { 39 | "message": "Example" 40 | }, 41 | "exclude": { 42 | "message": "Exclude..." 43 | }, 44 | "excludeUrl": { 45 | "message": "page" 46 | }, 47 | "excludeUrlPrefix": { 48 | "message": "page/and/deeper" 49 | }, 50 | "excludeDomain": { 51 | "message": "entire domain" 52 | }, 53 | "excludedPages": { 54 | "message": "Excluded pages or patterns" 55 | }, 56 | "export": { 57 | "message": "Export" 58 | }, 59 | "failedExcluded": { 60 | "message": "The page URL is excluded in options" 61 | }, 62 | "failedUnpageable": { 63 | "message": "No pageable content found" 64 | }, 65 | "failedUnsupported": { 66 | "message": "Browser UI or extension pages aren't supported" 67 | }, 68 | "genericRules": { 69 | "message": "Try generic rules" 70 | }, 71 | "genericRulesEnableHint": { 72 | "message": "Enable it in the options first, please" 73 | }, 74 | "genericRulesEnabled": { 75 | "message": "Enable generic rules on sites/patterns" 76 | }, 77 | "genericRulesInfo": { 78 | "message": "<*> means all, other examples are under the excluded pages below" 79 | }, 80 | "hotkeys": { 81 | "message": "Hotkeys" 82 | }, 83 | "import": { 84 | "message": "Import" 85 | }, 86 | "loadMore": { 87 | "message": "Load more..." 88 | }, 89 | "loading": { 90 | "message": "Loading" 91 | }, 92 | "off": { 93 | "message": "Off" 94 | }, 95 | "ok": { 96 | "message": "OK" 97 | }, 98 | "on": { 99 | "message": "On" 100 | }, 101 | "onOff": { 102 | "message": "On/off" 103 | }, 104 | "optionalRare": { 105 | "message": "(optional, very rare)" 106 | }, 107 | "options": { 108 | "message": "Options" 109 | }, 110 | "overwriteSettings": { 111 | "message": "Overwrite rules and exclusions on import" 112 | }, 113 | "page": { 114 | "message": "Page:" 115 | }, 116 | "pageHeightThreshold": { 117 | "message": "Remaining page height (in pixels)" 118 | }, 119 | "pageHeightThresholdInfo": { 120 | "message": "A bigger value means that prefetching starts earlier while you scroll the current page, and a really big value would start prefetching immediately" 121 | }, 122 | "regexp": { 123 | "message": "regexp" 124 | }, 125 | "requestInterval": { 126 | "message": "Minimum page request interval (in seconds)" 127 | }, 128 | "restore": { 129 | "message": "Restore" 130 | }, 131 | "saveChanges": { 132 | "message": "Save changes" 133 | }, 134 | "singleURL": { 135 | "message": "single URL" 136 | }, 137 | "siteinfo": { 138 | "message": "Siteinfo" 139 | }, 140 | "size": { 141 | "message": "Size" 142 | }, 143 | "status": { 144 | "message": "Status" 145 | }, 146 | "statusStyle": { 147 | "message": "Status bar custom CSS" 148 | }, 149 | "statusStyleLabel": { 150 | "message": "Standard" 151 | }, 152 | "statusStyleErrorLabel": { 153 | "message": "Error" 154 | }, 155 | "statusStyleInfo": { 156 | "message": "Leave empty and save to use the defaults" 157 | }, 158 | "stop": { 159 | "message": "Stop" 160 | }, 161 | "unloadAfter": { 162 | "message": "Inactivity timeout before unloading (in minutes)" 163 | }, 164 | "unloadAfterInfo": { 165 | "message": "unloading the background script saves memory but stresses CPU to compile thousands of rules on each subsequent restart, <-1> = <1440> = maximum (one day), <0> = native behavior (30 seconds), <1> = default" 166 | }, 167 | "updateSiteinfo": { 168 | "message": "Update siteinfo" 169 | }, 170 | "wildcard": { 171 | "message": "wildcard" 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /_locales/ja/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "customRules": { 3 | "message": "追加の定義" 4 | }, 5 | "description": { 6 | "message": "ページごとに分けられたWebページを自動で読み込み継ぎ足し表示を行うブラウザ拡張です。 AutoPagerizeは様々なWebサイトで利用でき、効率的なWebブラウジングを提供します。" 7 | }, 8 | "showStatus": { 9 | "message": "メッセージバーを表示" 10 | }, 11 | "error": { 12 | "message": "エラー" 13 | }, 14 | "example": { 15 | "message": "例" 16 | }, 17 | "excludedPages": { 18 | "message": "除外パターン" 19 | }, 20 | "loading": { 21 | "message": "ロード中" 22 | }, 23 | "off": { 24 | "message": "無効にする" 25 | }, 26 | "on": { 27 | "message": "有効にする" 28 | }, 29 | "options": { 30 | "message": "設定" 31 | }, 32 | "regexp": { 33 | "message": "正規表現" 34 | }, 35 | "save": { 36 | "message": "保存" 37 | }, 38 | "siteinfo": { 39 | "message": "サイト情報" 40 | }, 41 | "size": { 42 | "message": "登録数" 43 | }, 44 | "status": { 45 | "message": "ステータス" 46 | }, 47 | "updateSiteinfo": { 48 | "message": "サイト情報を更新する" 49 | }, 50 | "wildcard": { 51 | "message": "ワイルドカード" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /_locales/ru/messages.json: -------------------------------------------------------------------------------- 1 | { 2 | "customRules": { 3 | "message": "Дополнительные правила" 4 | }, 5 | "description": { 6 | "message": "Расширение для браузера для авто-загрузки последующих страниц на сайтах которые это поддерживают AutoPagerize поддерживает множество сайтов, повышая эффективность веб серфинга." 7 | }, 8 | "showStatus": { 9 | "message": "Отображать информационную панель" 10 | }, 11 | "error": { 12 | "message": "Ошибка" 13 | }, 14 | "example": { 15 | "message": "Пример" 16 | }, 17 | "excludedPages": { 18 | "message": "Отключить на следующих сайтах" 19 | }, 20 | "loading": { 21 | "message": "Загрузка" 22 | }, 23 | "off": { 24 | "message": "Выкл" 25 | }, 26 | "on": { 27 | "message": "Вкл" 28 | }, 29 | "options": { 30 | "message": "Настройки" 31 | }, 32 | "save": { 33 | "message": "Сохранить" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /bg/bg-api.js: -------------------------------------------------------------------------------- 1 | import {getActiveTab, ignoreLastError, tabSend} from '/util/common.js'; 2 | import {dbExec} from '/util/storage-idb.js'; 3 | import {buildGenericRules} from './bg-filter.js'; 4 | import {setIcon} from './bg-icon.js'; 5 | import {launch} from './bg-launch.js'; 6 | import {writeSettings} from './bg-settings.js'; 7 | import {switchGlobalState} from './bg-switch.js'; 8 | import {updateSiteinfo} from './bg-update.js'; 9 | import {isUrlExcluded} from './bg-util.js'; 10 | import {g, getGenericRules, onNavigation} from './bg.js'; 11 | import {offscreen} from './bg-offscreen.js'; 12 | 13 | let POPUP; 14 | 15 | const api = { 16 | __proto__: null, 17 | isUrlExcluded: url => g.cfg instanceof Promise 18 | ? g.cfg.then(() => isUrlExcluded(url)) 19 | : isUrlExcluded(url), 20 | /** @this {chrome.runtime.MessageSender} */ 21 | launched() { 22 | const tabId = this.tab.id; 23 | if (!POPUP) POPUP = chrome.runtime.getManifest().action.default_popup.split('?')[0]; 24 | chrome.action.setPopup({tabId, popup: POPUP}); 25 | setIcon({tabId}); 26 | }, 27 | reinject: opts => onNavigation({...opts, frameId: 0}, true), 28 | setIcon, 29 | switchGlobalState, 30 | tryGenericRules: async tabId => launch(tabId, await getGenericRules(), {lastTry: 'genericRules'}), 31 | updateSiteinfo, 32 | writeSettings, 33 | }; 34 | 35 | chrome.alarms.onAlarm.addListener(() => { 36 | updateSiteinfo(''); 37 | }); 38 | 39 | chrome.contextMenus.onClicked.addListener(info => { 40 | switchGlobalState(info.checked); 41 | }); 42 | 43 | chrome.commands.onCommand.addListener(async cmd => { 44 | if (cmd === 'onOff') { 45 | await g.cfg; 46 | return switchGlobalState(!g.cfg.enabled); 47 | } 48 | if (cmd.startsWith('loadMore')) { 49 | return tabSend((await getActiveTab()).id, ['run', {loadMore: +cmd.slice(-2)}]); 50 | } 51 | }); 52 | 53 | chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { 54 | const fn = api[msg.action]; 55 | if (!fn) 56 | return; 57 | const result = fn.apply(sender, msg.data); 58 | if (result && typeof result.then === 'function') { 59 | result.then(sendResponse); 60 | return true; 61 | } 62 | if (result !== undefined) 63 | sendResponse(result); 64 | }); 65 | 66 | chrome.runtime.onInstalled.addListener(async info => { 67 | if (info.reason !== 'update' && info.reason !== 'install') 68 | return; 69 | 70 | chrome.contextMenus.create({ 71 | id: 'onOff', 72 | type: 'checkbox', 73 | contexts: ['action'], 74 | title: chrome.i18n.getMessage('onOff'), 75 | }, ignoreLastError); 76 | 77 | if (info.previousVersion <= '1.0.6') { 78 | buildGenericRules(); 79 | chrome.storage.local.clear(); 80 | const keys = ['cacheDate', 'enabled']; 81 | const {cacheDate, enabled} = await offscreen.localStorageGet(keys); 82 | const cd = new Date(+cacheDate); 83 | keys.push('fixes', 'orphanMessageId'); 84 | offscreen.localStorageSet(Object.fromEntries(keys.map(k => [k]))); 85 | dbExec({store: 'data'}).put(+cd ? cd : new Date(), 'cacheDate'); 86 | if (enabled === 'false') 87 | return; 88 | } 89 | 90 | switchGlobalState(true); 91 | }); 92 | -------------------------------------------------------------------------------- /bg/bg-filter.js: -------------------------------------------------------------------------------- 1 | import {arrayOrDummy, isGenericUrl} from '/util/common.js'; 2 | import {dbExec} from '/util/storage-idb.js'; 3 | import {readMissingRules} from './bg-unpack.js'; 4 | import {calcRuleKey, ruleKeyToUrl, str2rx} from './bg-util.js'; 5 | import {cache, cacheKeys, g} from './bg.js'; 6 | 7 | export function buildGenericRules() { 8 | return buildGenericRulesImpl.busy || (buildGenericRulesImpl.busy = buildGenericRulesImpl()); 9 | } 10 | 11 | async function buildGenericRulesImpl() { 12 | if (!cacheKeys.size) 13 | await (loadCacheKeys.busy || (loadCacheKeys.busy = loadCacheKeys())); 14 | const rules = []; 15 | const toRead = []; 16 | for (const key of cacheKeys.values()) 17 | if (isGenericUrl(key.url)) 18 | rules.push(cache.get(key.id) || toRead.push([rules.length, key.id])); 19 | if (toRead.length) 20 | await readMissingRules(rules, toRead); 21 | dbExec({store: 'data'}).put(rules, 'genericRules'); 22 | buildGenericRulesImpl.busy = null; 23 | return rules; 24 | } 25 | 26 | export async function filterCache(url, urlCacheKey, packedRules) { 27 | if (!cacheKeys.size) 28 | await (loadCacheKeys.busy || (loadCacheKeys.busy = loadCacheKeys())); 29 | if (!cacheKeys.size) 30 | await (buildSiteinfo.busy || (buildSiteinfo.busy = loadBuiltinSiteinfo())); 31 | if (cacheKeys.values().next().value.rx === undefined) 32 | regexpifyCache(); 33 | const customRules = arrayOrDummy(g.cfg.rules); 34 | if (customRules.length && !customRules[0].hasOwnProperty('rx')) 35 | regexpifyCustomRules(); 36 | const toUse = []; 37 | const toWrite = []; 38 | const toRead = []; 39 | for (let i = 0, len = customRules.length; i < len; i++) { 40 | const rule = customRules[i]; 41 | if (rule.rx && rule.rx.test(url)) { 42 | toUse.push(rule); 43 | toWrite.push(-i - 1); 44 | } 45 | } 46 | for (const key of cacheKeys.values()) { 47 | const {rx} = key; 48 | if (!isGenericUrl(key.url) && rx && 49 | (!rx.txt 50 | ? rx.test(url) 51 | : (rx.atStart ? url.startsWith(rx.txt) : url.includes(rx.txt)) || 52 | rx.txt2 && (rx.atStart ? url.startsWith(rx.txt2) : url.includes(rx.txt2))) 53 | ) { 54 | const rule = cache.get(key.id); 55 | if (!rule) 56 | toRead.push([toUse.length, key.id]); 57 | toUse.push(rule); 58 | toWrite.push(key.id); 59 | } 60 | } 61 | if (toRead.length) 62 | await readMissingRules(toUse, toRead); 63 | if (urlCacheKey && `${toWrite}` !== `${packedRules}`) 64 | dbExec({store: 'urlCache'}).put(new Int32Array(toWrite), urlCacheKey); 65 | return toUse; 66 | } 67 | 68 | async function loadCacheKeys() { 69 | const keys = arrayOrDummy(await dbExec.getAllKeys()); 70 | // currently URLs don't have weird characters so the length delta in UTF8 is same as in UTF16 71 | keys.sort((a, b) => b.length - a.length); 72 | cacheKeys.clear(); 73 | for (const key of keys) { 74 | const rule = { 75 | url: ruleKeyToUrl(key), 76 | id: new Uint32Array(key.buffer || key, 0, 1)[0], 77 | rx: undefined, 78 | }; 79 | cacheKeys.set(rule.id, rule); 80 | } 81 | loadCacheKeys.busy = null; 82 | } 83 | 84 | function regexpifyCache() { 85 | // many rules have an unescaped '.' in host name so we'll treat it same as '\.' 86 | const rxTrivial = /^(\^?)https?(\??):\/\/([-\w]*\\?\.)+[-\w/]*$/; 87 | for (const key of cacheKeys.values()) { 88 | let rx; 89 | const {url} = key; 90 | // provides a ~2x speed-up for the first run of filterCache() 91 | // and reduces the memory consumption by a few megs 92 | // by recognizing trivial/literal url expressions 93 | // (50% of 4000 rules at the moment) 94 | if (rxTrivial.test(url)) { 95 | const atStart = RegExp.$1 === '^'; 96 | const hasQuestion = RegExp.$2; 97 | const txt = (hasQuestion ? url.replace('https?', 'http') : url).replace(/[\\?^]/g, ''); 98 | const txt2 = hasQuestion ? 'https' + txt.slice(4) : ''; 99 | rx = {atStart, txt, txt2}; 100 | } else { 101 | try { 102 | rx = RegExp(url); 103 | } catch (e) { 104 | rx = null; 105 | } 106 | } 107 | Object.defineProperty(key, 'rx', {value: rx}); 108 | } 109 | } 110 | 111 | function regexpifyCustomRules() { 112 | for (const r of g.cfg.rules) { 113 | const {url} = r; 114 | let rx = str2rx.get(url); 115 | if (rx === null) 116 | continue; 117 | if (!rx) { 118 | try { 119 | rx = RegExp(url); 120 | } catch (e) { 121 | rx = null; 122 | } 123 | str2rx.set(url, rx); 124 | } 125 | Object.defineProperty(r, 'rx', {value: rx}); 126 | } 127 | } 128 | 129 | async function loadBuiltinSiteinfo() { 130 | const [si] = await Promise.all([ 131 | (await fetch('/siteinfo.json')).json(), 132 | dbExec.clear(), 133 | dbExec({store: 'urlCache'}).clear(), 134 | ]); 135 | return buildSiteinfo(si); 136 | } 137 | 138 | export async function buildSiteinfo(si, fnCanWrite) { 139 | cache.clear(); 140 | cacheKeys.clear(); 141 | const gr = []; 142 | let /** @type IDBObjectStore */ store, op; 143 | for (const rule of si) { 144 | const {id, url} = rule; 145 | cache.set(id, rule); 146 | cacheKeys.set(id, rule); 147 | if (isGenericUrl(url)) 148 | gr.push(rule); 149 | if (!fnCanWrite || fnCanWrite(rule)) { 150 | if (!store) 151 | store = await dbExec.WRITE; 152 | op = store.put({ 153 | ...rule, 154 | url: calcRuleKey(rule), 155 | }); 156 | op.onerror = console.error; 157 | } 158 | } 159 | g.genericRules = gr; 160 | store = await dbExec({store: 'data'}).WRITE; 161 | store.put(new Date(), 'cacheDate'); 162 | store.put(gr, 'genericRules'); 163 | buildSiteinfo.busy = null; 164 | } 165 | -------------------------------------------------------------------------------- /bg/bg-icon.js: -------------------------------------------------------------------------------- 1 | // Purpose: speed up successive calls, especially in switchGlobalState() 2 | import {ignoreLastError} from '/util/common.js'; 3 | 4 | const iconCache = {}; 5 | let iconBaseDir; 6 | 7 | export async function setIcon({tabId, type = ''}) { 8 | let res = iconCache[type] || (iconCache[type] = loadFromSource(type)); 9 | if (res.then) res = iconCache[type] = await res; 10 | chrome.action.setIcon({tabId, imageData: res}, ignoreLastError); 11 | } 12 | 13 | async function loadFromSource(type = '') { 14 | if (!iconBaseDir) 15 | // strip the leading '/' and the file name 16 | iconBaseDir = chrome.runtime.getManifest().icons['16'].replace(/^\/|[^/]+$/g, ''); 17 | const dir = `/${iconBaseDir}${type ? type + '/' : ''}`; 18 | const results = await Promise.all([16, 32, 48].map(readIcon, dir)); 19 | return Object.fromEntries(results); 20 | } 21 | 22 | /** @this {String} */ 23 | async function readIcon(size) { 24 | const img = await createImageBitmap(await (await fetch(`${this}${size}.png`)).blob()); 25 | const {width: w, height: h} = img; 26 | const ctx = new OffscreenCanvas(w, h).getContext('2d'); 27 | ctx.drawImage(img, 0, 0, w, h); 28 | return [size, ctx.getImageData(0, 0, w, h)]; 29 | } 30 | -------------------------------------------------------------------------------- /bg/bg-launch.js: -------------------------------------------------------------------------------- 1 | import {DEFAULTS, doDelay, getActiveTab, RETRY_TIMEOUT, tabSend} from '/util/common.js'; 2 | import {PROPS_TO_NOTIFY} from './bg-util.js'; 3 | import {g} from './bg.js'; 4 | 5 | /** 6 | * @return {Promise} 7 | * true if there's an applicable rule (used by lastTry='genericRules' mode) 8 | */ 9 | export async function launch(tabId, rules, {lastTry, first, url}) { 10 | let rr; 11 | let delay = g.cfg.requestInterval; 12 | if (first) 13 | await execScript(tabId, ['xpather.js']); 14 | while (!( 15 | await doDelay(delay), 16 | rr = await tabSend(tabId, ['checkRules', rules]) 17 | )) { 18 | if (rr === undefined) // navigated to another doc 19 | return; 20 | if (lastTry) 21 | break; 22 | lastTry = true; 23 | delay = RETRY_TIMEOUT; 24 | } 25 | if (!rr || lastTry === 'genericRules') 26 | return rr; 27 | if (!rr?.run) 28 | await execScript(tabId, [ 29 | 'pager.js', 30 | url && (rr = url.indexOf('.google.')) > 0 && rr < url.indexOf('/', 8) && 31 | 'fix-google.js', 32 | ].filter(Boolean)); 33 | const ss = {}; 34 | for (const name of PROPS_TO_NOTIFY) 35 | ss[name] = g.cfg[name] ?? DEFAULTS[name]; 36 | await tabSend(tabId, ['launch', ss, first]); 37 | } 38 | 39 | async function execScript(tabId, names) { 40 | try { 41 | const [{result}] = await chrome.scripting.executeScript({ 42 | target: {tabId: tabId ?? (await getActiveTab()).id}, 43 | files: names.map(n => '/content/' + n), 44 | }); 45 | return result; 46 | } catch (err) {} 47 | } 48 | -------------------------------------------------------------------------------- /bg/bg-offscreen.js: -------------------------------------------------------------------------------- 1 | export const offscreen = new Proxy({}, { 2 | get: (_, cmd) => exec.bind(null, cmd), 3 | }); 4 | 5 | /** @type {{[id: string]: PromiseWithResolvers & {stack: string}}} */ 6 | let queue; 7 | /** @type {MessagePort} */ 8 | let port; 9 | 10 | async function exec(cmd, ...args) { 11 | if (!port) 12 | await init(); 13 | const pr = Promise.withResolvers(); 14 | const id = performance.now(); 15 | pr.stack = new Error().stack; 16 | queue[id] = pr; 17 | port.postMessage({cmd, args, id}); 18 | return pr.promise; 19 | } 20 | 21 | async function init() { 22 | let client; 23 | for (let retry = 0; retry < 2; retry++) { 24 | const url = chrome.runtime.getURL('/bg/offscreen.html'); 25 | client = (await self.clients.matchAll({includeUncontrolled: true})).find(c => c.url === url); 26 | if (client || retry) 27 | break; 28 | try { 29 | await chrome.offscreen.createDocument({ 30 | url, 31 | reasons: ['LOCAL_STORAGE'], 32 | justification: 'Yes', 33 | }); 34 | } catch (err) { 35 | if (!err.message.startsWith('Only a single offscreen')) 36 | throw err; 37 | } 38 | } 39 | const mc = new MessageChannel(); 40 | const pr = Promise.withResolvers(); 41 | client.postMessage(null, [mc.port2]); 42 | port = mc.port1; 43 | port.onmessage = pr.resolve; 44 | await pr.promise; 45 | port.onmessage = onmessage; 46 | queue = {'-1': {reject: done}}; 47 | } 48 | 49 | /** @param {MessageEvent} _ */ 50 | function onmessage({data: {id, res, err}}) { 51 | const v = queue[id]; 52 | delete queue[id]; 53 | if (!err) v.resolve(res); 54 | else { 55 | if (v.stack) err.stack += '\n' + v.stack; 56 | v.reject(err); 57 | } 58 | } 59 | 60 | function done(err) { 61 | chrome.offscreen.closeDocument(); 62 | for (const v of Object.values(queue)) 63 | v.reject((err.stack = v.stack, err)); 64 | port = queue = null; 65 | } 66 | -------------------------------------------------------------------------------- /bg/bg-settings.js: -------------------------------------------------------------------------------- 1 | import {DEFAULTS, ignoreLastError, getLZ} from '/util/common.js'; 2 | import {trimUrlCache} from './bg-trim.js'; 3 | import {PROPS_TO_NOTIFY, queryTabs} from './bg-util.js'; 4 | import {offscreen} from './bg-offscreen.js'; 5 | import {g, keepAlive} from './bg.js'; 6 | 7 | export async function writeSettings(ss) { 8 | const all = g.cfg instanceof Promise ? await g.cfg : g.cfg; 9 | if (ss.rules) 10 | trimUrlCache(all.rules, ss.rules, {main: false}); 11 | const toWrite = {}; 12 | let toNotify; 13 | for (const k in ss) { 14 | const v = ss[k] ?? DEFAULTS[k]; 15 | if (v !== all[k]) { 16 | all[k] = v; 17 | toWrite[k] = v && getLZ(k, v, true); 18 | if (!toNotify) toNotify = PROPS_TO_NOTIFY.includes(k); 19 | } 20 | } 21 | chrome.storage.sync.set(toWrite); 22 | localStorageMirror(toWrite, 'darkTheme'); 23 | if (toNotify) 24 | notify(all); 25 | keepAlive(); 26 | } 27 | 28 | async function localStorageMirror(ss, key) { 29 | const val = ss[key]; 30 | const stored = val != null && await offscreen.localStorageGet(key) != null; 31 | if (val ? !stored : stored) 32 | await offscreen.localStorageSet({[key]: val ? '' : null}); 33 | } 34 | 35 | async function notify(ss = g.cfg) { 36 | const a1 = {}; 37 | const opts = { 38 | target: {tabId: 0}, 39 | func: settings => typeof run === 'function' && self.run({settings}), 40 | args: [a1], 41 | }; 42 | for (const p of PROPS_TO_NOTIFY) 43 | a1[p] = ss[p]; 44 | for (const tab of await queryTabs()) { 45 | opts.target.tabId = tab.id; 46 | chrome.scripting.executeScript(opts, ignoreLastError); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /bg/bg-switch.js: -------------------------------------------------------------------------------- 1 | import {tabSend} from '/util/common.js'; 2 | import {setIcon} from './bg-icon.js'; 3 | import {onNavigation, toggleNav} from './bg.js'; 4 | import {queryTabs} from './bg-util.js'; 5 | 6 | let busy, stopIt; 7 | 8 | export async function switchGlobalState(state) { 9 | if (busy) 10 | await (stopIt = Promise.withResolvers()).promise; 11 | busy = true; 12 | stopIt = false; 13 | chrome.contextMenus.update('onOff', {checked: state}); 14 | toggleNav(state); 15 | await (state ? activate() : deactivate()); 16 | busy = false; 17 | } 18 | 19 | async function activate() { 20 | chrome.storage.sync.remove('enabled'); 21 | for (const {id, url} of await queryTabs()) { 22 | await onNavigation({url, tabId: id, frameId: 0}); 23 | if (stopIt) return stopIt.resolve(); 24 | } 25 | } 26 | 27 | async function deactivate() { 28 | chrome.storage.sync.set({enabled: false}); 29 | for (const t of await queryTabs()) { 30 | await setIcon({tabId: t.id, type: 'off'}); 31 | if (!t.discarded) 32 | await tabSend(t.id, ['run', {terminate: true}]); 33 | if (stopIt) 34 | return stopIt.resolve(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /bg/bg-trim.js: -------------------------------------------------------------------------------- 1 | import {arrayOrDummy} from '/util/common.js'; 2 | import {dbExec} from '/util/storage-idb.js'; 3 | 4 | let state; 5 | 6 | export async function trimUrlCache(oldRules, newRules, {main = true} = {}) { 7 | if (state) 8 | return; 9 | state = { 10 | main, 11 | old: convertToMap(oldRules), 12 | new: convertToMap(newRules), 13 | }; 14 | const store = await dbExec({store: 'urlCache'}).WRITE; 15 | if (someUrlChanged()) { 16 | await store.clear(); 17 | } else { 18 | const op = store.openCursor(); 19 | const pr = Promise.withResolvers(); 20 | op.onsuccess = processCursor; 21 | op.onerror = pr.reject; 22 | op.__resolve = pr.resolve; 23 | await pr.promise; 24 | } 25 | state = null; 26 | } 27 | 28 | export function convertToMap(obj) { 29 | return obj instanceof Map ? obj 30 | : new Map(arrayOrDummy(obj).map((x, i) => [-i - 1, x])); 31 | } 32 | 33 | function someUrlChanged() { 34 | const newRules = state.new; 35 | if (state.old.size !== newRules.size) 36 | return true; 37 | for (const r of state.old.values()) 38 | if (r.url !== (newRules.get(r.id) || {}).url) 39 | return true; 40 | } 41 | 42 | function someRuleChanged(packedRules) { 43 | for (let id of packedRules) { 44 | if (id < 0) { 45 | if (state.main) 46 | continue; 47 | id = -id - 1; 48 | } else if (!state.main) 49 | continue; 50 | const a = state.old.get(id); 51 | const b = state.new.get(id); 52 | if (!a || !b) 53 | return true; 54 | for (const k in a) 55 | if (a[k] !== b[k]) 56 | return true; 57 | for (const k in b) 58 | if (!a.hasOwnProperty(k)) 59 | return true; 60 | } 61 | } 62 | 63 | function processCursor({target: op}) { 64 | const cursor = /** IDBCursorWithValue */ op.result; 65 | if (cursor) { 66 | if (someRuleChanged(cursor.value)) 67 | cursor.delete(); 68 | cursor.continue(); 69 | } else { 70 | op.__resolve(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /bg/bg-unpack.js: -------------------------------------------------------------------------------- 1 | import {arrayOrDummy} from '/util/common.js'; 2 | import {dbExec} from '/util/storage-idb.js'; 3 | import {ruleKeyToUrl} from './bg-util.js'; 4 | import {cache, cacheKeys, g} from './bg.js'; 5 | 6 | // (!) `cfg` must be already loaded 7 | export async function unpackRules(packedRules) { 8 | const customRules = arrayOrDummy(g.cfg.rules); 9 | const unpackedRules = []; 10 | const toRead = []; 11 | for (const id of packedRules) { 12 | let r; 13 | if (id < 0) { 14 | r = customRules[-id - 1]; 15 | if (!r) 16 | return; 17 | } else { 18 | r = cache.get(id); 19 | !r && toRead.push([unpackedRules.length, id]); 20 | } 21 | unpackedRules.push(r); 22 | } 23 | return toRead.length 24 | ? readMissingRules(unpackedRules, toRead) 25 | : unpackedRules; 26 | } 27 | 28 | export async function readMissingRules(rules, toRead) { 29 | const pr = Promise.withResolvers(); 30 | const index = await dbExec({index: 'id'}).READ; 31 | index.__rules = rules; 32 | let /** @type Req */ op; 33 | for (const [arrayPos, id] of toRead) { 34 | op = index.get(id); 35 | op.__arrayPos = arrayPos; 36 | op.onsuccess = readRule; 37 | op.onerror = console.error; 38 | } 39 | op.__resolve = pr.resolve; 40 | op.onerror = () => pr.resolve(false); 41 | return pr.promise; 42 | } 43 | 44 | function readRule(e) { 45 | const op = /** @type Req */ e.target; 46 | const r = op.result; 47 | if (!r) { 48 | op.transaction.abort(); 49 | return; 50 | } 51 | const old = cacheKeys.get(r.id); 52 | if (!old) 53 | r.url = ruleKeyToUrl(r.url); 54 | else { 55 | r.url = old.url; 56 | 'rx' in old && Object.defineProperty(r, 'rx', {value: old.rx}); 57 | } 58 | cache.set(r.id, r); 59 | op.source.__rules[op.__arrayPos] = r; 60 | if (op.__resolve) 61 | op.__resolve(op.source.__rules); 62 | } 63 | 64 | /** 65 | * @typedef {IDBRequest & { 66 | * __resolve: function, 67 | * __arrayPos: number, 68 | * source: IDBIndex & {__rules: {}}, 69 | * }} Req 70 | */ 71 | -------------------------------------------------------------------------------- /bg/bg-update.js: -------------------------------------------------------------------------------- 1 | import {offscreen} from './bg-offscreen.js'; 2 | import {arrayOrDummy} from '/util/common.js'; 3 | import {dbExec} from '/util/storage-idb.js'; 4 | import {buildGenericRules, buildSiteinfo} from './bg-filter.js'; 5 | import {trimUrlCache} from './bg-trim.js'; 6 | import {calcRuleKey, ruleKeyToUrl} from './bg-util.js'; 7 | import {cache, cacheKeys, keepAlive} from './bg.js'; 8 | 9 | const DATA_URL = 'http://wedata.net/databases/AutoPagerize/items_all.json'; 10 | const KNOWN_KEYS = [ 11 | 'url', 12 | 'nextLink', 13 | 'insertBefore', 14 | 'pageElement', 15 | ]; 16 | 17 | chrome.alarms.get('update', a => { 18 | const p = 24 * 60; // 1 day 19 | if (!a || a.periodInMinutes !== p) 20 | chrome.alarms.create('update', {periodInMinutes: p, when: Date.now() + 60e3}); 21 | }); 22 | 23 | export async function updateSiteinfo(portName) { 24 | try { 25 | keepAlive(true); 26 | const opts = {headers: {'Cache-Control': 'no-cache'}}; 27 | /** @type {Map[]} */ 28 | const [old, fresh] = await Promise.all([ 29 | getCacheIndexedById(), 30 | (portName 31 | ? offscreen.xhr(DATA_URL, {...opts, portName, timeout: /*same as fetch*/ 300e3}) 32 | : fetch(DATA_URL, {...opts}).then(r => r.text()) 33 | ).then(sanitize), 34 | ]); 35 | keepAlive(); 36 | if (!fresh.size) 37 | return 0; 38 | await removeObsoleteRules(old, fresh); 39 | await trimUrlCache(old, fresh); 40 | await buildSiteinfo.busy; 41 | await buildSiteinfo(fresh.values(), rule => !shallowEqual(rule, old.get(rule.id))); 42 | buildGenericRules(); 43 | return fresh.size; 44 | } catch (e) { 45 | return `${e.target?.error || e}`; 46 | } 47 | } 48 | 49 | function sanitize(data) { 50 | data = arrayOrDummy(JSON.parse(data)); 51 | const map = new Map(); 52 | let len = 0; 53 | for (let i = 0, v; i < data.length; i++) { 54 | v = data[i]; 55 | if (v?.data?.url) data[len++] = pickKnownKeys(v.data, v.resource_url); 56 | } 57 | data.length = len; 58 | data.sort((a, b) => a.id - b.id); 59 | for (const v of data) map.set(v.id, v); 60 | return map; 61 | } 62 | 63 | function pickKnownKeys(entry, resourceUrl) { 64 | for (const key of Object.keys(entry)) { 65 | if (!KNOWN_KEYS.includes(key)) { 66 | const newEntry = {}; 67 | for (const k of KNOWN_KEYS) { 68 | const v = entry[k]; 69 | if (v !== undefined) 70 | newEntry[k] = v; 71 | } 72 | entry = newEntry; 73 | break; 74 | } 75 | } 76 | entry.id = Number(resourceUrl.slice(resourceUrl.lastIndexOf('/') + 1)); 77 | return entry; 78 | } 79 | 80 | async function getCacheIndexedById() { 81 | if (cache.size && cache.size === cacheKeys.size) 82 | return cache; 83 | const all = await dbExec.getAll(); 84 | const byId = new Map(); 85 | for (const r of all) { 86 | r.url = ruleKeyToUrl(r.url); 87 | byId.set(r.id, r); 88 | } 89 | return byId; 90 | } 91 | 92 | async function removeObsoleteRules(old, fresh) { 93 | let /** @type IDBObjectStore */ store, op; 94 | for (const a of old.values()) { 95 | const b = fresh.get(a.id); 96 | if (b && b.url === a.url) 97 | continue; 98 | if (!store) 99 | store = await dbExec.WRITE; 100 | op = store.delete(calcRuleKey(a)); 101 | } 102 | if (op) { 103 | const pr = Promise.withResolvers(); 104 | op.onsuccess = pr.resolve; 105 | op.onerror = pr.reject; 106 | await pr.promise; 107 | } 108 | } 109 | 110 | function shallowEqual(a, b) { 111 | if (!a !== !b) 112 | return; 113 | for (const k in a) 114 | if (a[k] !== b[k]) 115 | return; 116 | for (const k in b) 117 | if (!a.hasOwnProperty(k)) 118 | return; 119 | return true; 120 | } 121 | -------------------------------------------------------------------------------- /bg/bg-util.js: -------------------------------------------------------------------------------- 1 | export const utf8encoder = new TextEncoder(); 2 | export const utf8decoder = new TextDecoder(); 3 | /** @type {Map} - null means a bad regexp */ 4 | export const str2rx = new Map(); 5 | 6 | import {arrayOrDummy} from '/util/common.js'; 7 | import {g} from './bg.js'; 8 | 9 | /** content scripts should be notified when these options are changed */ 10 | export const PROPS_TO_NOTIFY = [ 11 | 'showStatus', 12 | 'statusStyle', 13 | 'statusStyleError', 14 | 'requestInterval', 15 | 'pageHeightThreshold', 16 | ]; 17 | 18 | // !!! Requires 'g.cfg' to be already loaded when no 'exclusions' were supplied 19 | export function isUrlExcluded(url) { 20 | return ( 21 | url.startsWith('https://mail.google.com/') || 22 | url.startsWith('http://b.hatena.ne.jp/') || 23 | isUrlMatched(url, g.cfg.exclusions) 24 | ); 25 | } 26 | 27 | export function isUrlMatched(url, patterns) { 28 | for (const entry of arrayOrDummy(patterns)) { 29 | const isRegexp = entry.startsWith('/') && entry.endsWith('/'); 30 | if (!isRegexp) { 31 | if (url === entry || url.endsWith('/') && url === entry + '/') 32 | return true; 33 | const i = entry.indexOf('*'); 34 | if (i < 0) 35 | continue; 36 | if (i === entry.length - 1 && url.startsWith(entry.slice(0, -1))) 37 | return true; 38 | } 39 | const rx = str2rx.get(entry); 40 | if (rx !== null && (rx || compilePattern(entry, isRegexp)).test(url)) 41 | return true; 42 | } 43 | } 44 | 45 | function compilePattern(str, isRegexp) { 46 | let rx; 47 | try { 48 | const rxStr = isRegexp 49 | ? str.slice(1, -1) 50 | : '^' + 51 | str.replace(/([-()[\]{}+?.$^|\\])/g, '\\$1') 52 | .replace(/\x08/g, '\\x08') 53 | .replace(/\*/g, '.*') + 54 | '$'; 55 | rx = RegExp(rxStr); 56 | } catch (e) { 57 | rx = null; 58 | } 59 | str2rx.set(str, rx); 60 | return rx; 61 | } 62 | 63 | export async function calcUrlCacheKey(url) { 64 | const bytes = utf8encoder.encode(url); 65 | const hash = await crypto.subtle.digest('SHA-256', bytes); 66 | return new Uint8Array(hash).slice(0, 16); 67 | } 68 | 69 | export function calcRuleKey(rule) { 70 | const url = utf8encoder.encode(rule.url); 71 | const key = new Uint8Array(url.length + 4); 72 | new Uint32Array(key.buffer, 0, 1)[0] = rule.id; 73 | key.set(url, 4); 74 | return key; 75 | } 76 | 77 | export function ruleKeyToUrl(key) { 78 | return utf8decoder.decode(key.slice(4)); 79 | } 80 | 81 | /** @returns {Promise} array of tabs, beginning with the active tab */ 82 | export async function queryTabs() { 83 | const res = await chrome.tabs.query({url: '*://*/*'}); 84 | const i = res.findIndex(t => t.active); 85 | res.unshift(...res.splice(i, 1)); 86 | return res; 87 | } 88 | -------------------------------------------------------------------------------- /bg/bg.js: -------------------------------------------------------------------------------- 1 | import {loadSettings, NOP, tabSend} from '/util/common.js'; 2 | import {dbExec} from '/util/storage-idb.js'; 3 | import {buildGenericRules, filterCache} from './bg-filter.js'; 4 | import {setIcon} from './bg-icon.js'; 5 | import {launch} from './bg-launch.js'; 6 | import {unpackRules} from './bg-unpack.js'; 7 | import {calcUrlCacheKey, isUrlExcluded, isUrlMatched} from './bg-util.js'; 8 | import './bg-api.js'; 9 | 10 | export const cache = new Map(); 11 | export const cacheKeys = new Map(); 12 | export const g = { 13 | genericRules: null, 14 | /** @type {Settings|Promise} */ 15 | cfg: loadSettings(), 16 | }; 17 | const processing = new Map(); 18 | let alive, lastAlive; 19 | 20 | toggleNav(true); 21 | 22 | g.cfg.then(ss => { 23 | g.cfg = ss; 24 | keepAlive(); 25 | if (!ss.enabled) 26 | toggleNav(false); 27 | }); 28 | 29 | export function getGenericRules() { 30 | return g.genericRules || ( 31 | g.genericRules = dbExec({store: 'data'}).get('genericRules').then(async res => ( 32 | g.genericRules = res || await buildGenericRules() 33 | )) 34 | ); 35 | } 36 | 37 | export function toggleNav(on) { 38 | const args = on ? [{url: [{urlPrefix: 'http'}]}] : []; 39 | const fn = on ? 'addListener' : 'removeListener'; 40 | chrome.webNavigation.onCommitted[fn](onCommitted, ...args); 41 | chrome.webNavigation.onHistoryStateUpdated[fn](onNavigation, ...args); 42 | chrome.webNavigation.onReferenceFragmentUpdated[fn](onNavigation, ...args); 43 | } 44 | 45 | function onCommitted(evt) { 46 | return onNavigation(evt, true); 47 | } 48 | 49 | /** 50 | * @param evt 51 | * @param [first] 52 | */ 53 | export async function onNavigation(evt, first) { 54 | if (evt.frameId) 55 | return; 56 | const {tabId, url, timeStamp: ts} = evt; 57 | const p = processing.get(tabId); 58 | if (!first && p?.url === url) 59 | return; 60 | const tab = await chrome.tabs.get(tabId).catch(NOP); 61 | if (!tab?.url) // skipping pre-rendered tabs 62 | return; 63 | processing.set(tabId, {url, ts}); 64 | if (g.cfg instanceof Promise) 65 | g.cfg = await g.cfg; 66 | if (!isUrlExcluded(url)) 67 | await maybeLaunch(tabId, url, first); 68 | else if (await tabSend(tabId, ['launched', {terminate: true}])) 69 | setIcon({tabId, type: 'off'}); 70 | lastAlive = performance.now(); 71 | if (processing.get(tabId)?.ts === ts) 72 | processing.delete(tabId); 73 | } 74 | 75 | async function maybeLaunch(tabId, url, first) { 76 | const key = await calcUrlCacheKey(url); 77 | const packedRules = await dbExec({store: 'urlCache'}).get(key); 78 | const rules = 79 | packedRules?.length && await unpackRules(packedRules) || 80 | await filterCache(url, key, packedRules); 81 | if (g.cfg.genericRulesEnabled && isUrlMatched(url, g.cfg.genericSites)) { 82 | const t = getGenericRules(); 83 | rules.push(...t.then ? await t : t); 84 | } 85 | if (rules.length) 86 | await launch(tabId, rules, {first, url}); 87 | } 88 | 89 | export function keepAlive(state = g.cfg.unloadAfter) { 90 | alive = state 91 | ? alive || setInterval(alivePulse, 25e3) 92 | : alive && clearInterval(alive); 93 | } 94 | 95 | function alivePulse() { 96 | let t; 97 | if (alive 98 | && performance.now() - lastAlive < 60e3 * ((t = g.cfg.unloadAfter) < 0 ? 1440 : t)) { 99 | chrome.runtime.getPlatformInfo(); 100 | } else { 101 | clearInterval(alive); 102 | alive = 0; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /bg/offscreen.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /bg/offscreen.js: -------------------------------------------------------------------------------- 1 | let port; 2 | let unloadTimer; 3 | 4 | const commands = { 5 | __proto__: null, 6 | localStorageGet(what) { 7 | if (typeof what === 'string') 8 | return localStorage[what]; 9 | if (!what) 10 | return Object.assign({}, localStorage); 11 | if (Array.isArray(what)) 12 | return what.reduce((res, k) => ((res[k] = localStorage[k]), res), {}); 13 | }, 14 | localStorageSet(obj) { 15 | for (const k in obj) { 16 | const v = obj[k]; 17 | if (v != null) localStorage[k] = v; 18 | else delete localStorage[k]; 19 | } 20 | }, 21 | xhr(url, opts = {}) { 22 | return new Promise((resolve, reject) => { 23 | const {headers, portName, ...xhrOpts} = opts; 24 | const xhr = new XMLHttpRequest(); 25 | xhr.open('GET', url); 26 | if (headers) 27 | for (const h in headers) 28 | xhr.setRequestHeader(h, headers[h]); 29 | Object.assign(xhr, xhrOpts); 30 | xhr.onload = () => resolve(xhr.response); 31 | xhr.onerror = reject; 32 | xhr.ontimeout = reject; 33 | if (portName) { 34 | const port = chrome.runtime.connect({name: portName}); 35 | xhr.onprogress = e => port.postMessage(e.loaded); 36 | xhr.onloadend = () => port.disconnect(); 37 | } 38 | xhr.send(); 39 | }); 40 | }, 41 | }; 42 | 43 | /** @param {MessageEvent} evt */ 44 | navigator.serviceWorker.addEventListener('message', evt => { 45 | port = evt.ports[0]; 46 | port.postMessage(null); 47 | port.onmessage = onBGmessage; 48 | }, {once: true}); 49 | 50 | navigator.serviceWorker.startMessages(); 51 | 52 | /** @param {MessageEvent} evt */ 53 | async function onBGmessage(evt) { 54 | const {data} = evt; 55 | let res, err; 56 | clearTimeout(unloadTimer); 57 | try { 58 | res = commands[data.cmd].apply(evt, data.args); 59 | if (res instanceof Promise) res = await res; 60 | } catch (e) { 61 | err = e; 62 | } 63 | port.postMessage({id: data.id, res, err}); 64 | unloadTimer = setTimeout(unload, 5e3); 65 | } 66 | 67 | function unload() { 68 | port.postMessage({id: -1, err: new Error('Offscreen timeout')}); 69 | } 70 | -------------------------------------------------------------------------------- /content/fix-google.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // show images 4 | window.run({ 5 | filter(doc) { 6 | const re = /["'](data:image[^"']+)["'].*?\[(.*?)]\W*_setImagesSrc/g; 7 | for (const {text} of doc.getElementsByTagName('script')) { 8 | if (!text.includes('_setImagesSrc')) 9 | continue; 10 | let m; 11 | while ((m = re.exec(text))) { 12 | const [, dataUrl, ids] = m; 13 | for (const id of ids.match(/[^,'"]+/g) || []) { 14 | let el = doc.getElementById(id); 15 | if (!el) continue; 16 | el.src = dataUrl.replace(/\\x([0-9a-f]{2})/gi, (_, code) => 17 | String.fromCharCode(parseInt(code, 16))); 18 | if ((el = el.closest('[style*="display:none"]'))) 19 | el.style.removeProperty('display'); 20 | } 21 | } 22 | } 23 | }, 24 | }); 25 | -------------------------------------------------------------------------------- /content/pager.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // IIFE simplifies complete unregistering for garbage collection 4 | (() => { 5 | const status = { 6 | /** @type {Boolean} */ 7 | enabled: null, 8 | /** @type {HTMLFrameElement} */ 9 | element: null, 10 | /** @type {Number} */ 11 | timer: 0, 12 | /** @type {String} */ 13 | style: '', 14 | /** @type {String} */ 15 | styleError: '', 16 | }; 17 | const filters = new Set(); 18 | const orphanMessageId = chrome.runtime.id; 19 | /** @type {Node|HTMLElement} */ 20 | let insertPoint; 21 | let lastRequestURL = ''; 22 | /** @type {Record} */ 23 | let loadedURLs = {}; 24 | /** @type {function(status)} */ 25 | let onPageProcessed; 26 | let pageNum = 0; 27 | let pagesRemaining = 0; 28 | let requestInterval = 2000; 29 | let requestTime = 0; 30 | let requestTimer = 0; 31 | let requestURL = ''; 32 | /** @type {Object} */ 33 | let rule; 34 | /** @type {IntersectionObserver} */ 35 | let xo; 36 | /** @type {?Element} */ 37 | let xoElem; 38 | 39 | window.run = cfg => { 40 | let v; 41 | if ((v = cfg.settings)) 42 | loadSettings(v); 43 | if ((v = cfg.filter)) 44 | filters.add(v); 45 | if ((v = cfg.launch) && (loadedURLs = {}, !maybeInit(...v))) 46 | setTimeout(maybeInit, requestInterval, v[0]); 47 | if ((v = cfg.loadMore)) 48 | return doLoadMore(v); 49 | if (cfg.terminate) 50 | terminate(); 51 | }; 52 | 53 | document.dispatchEvent(new Event('GM_AutoPagerizeLoaded', {bubbles: true})); 54 | 55 | function maybeInit(rules, rule) { 56 | // content scripts may get unloaded during setTimeout 57 | if (!self.xpather?.MICROFORMAT) 58 | return terminate(); 59 | if (loadedURLs[location.href]) 60 | return true; 61 | if (!rule) 62 | rule = xpather.getMatchingRule(rules); 63 | if (rule) { 64 | init(rule); 65 | return true; 66 | } 67 | } 68 | 69 | function init(matchedRule) { 70 | pageNum = 1; 71 | rule = matchedRule; 72 | requestURL = getNextURL(rule.nextLink, document, location.href); 73 | if (!requestURL) 74 | return; 75 | let el = rule.insertBefore; 76 | if (!(insertPoint = el && xpather.getFirst(el))) { 77 | el = xpather.getLast(rule.pageElement); 78 | if (!el) return; 79 | insertPoint = ensureNextSibling(el); 80 | } 81 | loadedURLs = {[location.href]: 1}; 82 | requestTime = performance.now(); 83 | addEventListener(orphanMessageId, terminate); 84 | chrome.runtime.sendMessage({action: 'launched'}); 85 | watchBottom(); 86 | } 87 | 88 | function ensureNextSibling(el) { 89 | return el.nextSibling || (el.after(' '), el.nextSibling); 90 | } 91 | 92 | function request({force, timer} = {}) { 93 | if (timer) 94 | requestTimer = 0; 95 | else if (requestTimer) 96 | return; 97 | const url = requestURL; 98 | if (!url || url === lastRequestURL || loadedURLs[url]) 99 | return; 100 | if (!url.startsWith(location.origin + '/')) { 101 | statusShow({error: chrome.i18n.getMessage('errorOrigin')}); 102 | return; 103 | } 104 | const remain = requestInterval - (performance.now() - requestTime); 105 | if (!force && remain > 0) { 106 | requestTimer = setTimeout(request, remain, {timer: true}); 107 | return; 108 | } 109 | requestTime = performance.now(); 110 | lastRequestURL = url; 111 | statusShow({loading: true}); 112 | 113 | const xhr = new XMLHttpRequest(); 114 | xhr.open('GET', url); 115 | xhr.responseType = 'document'; 116 | xhr.timeout = 60e3; 117 | xhr.onload = e => { 118 | const ok = addPage(e, force); 119 | onPageProcessed?.(ok); 120 | }; 121 | xhr.onerror = xhr.ontimeout = e => { 122 | statusShow({error: e.message || e}); 123 | onPageProcessed?.(false); 124 | }; 125 | xhr.send(); 126 | return true; 127 | } 128 | 129 | /** 130 | * @return boolean - true if there are more pages 131 | */ 132 | function addPage(event) { 133 | const url = requestURL; 134 | const doc = event.target.response; 135 | // SHOULD PRECEDE stripping of scripts since a filter may need to process one 136 | for (const f of filters) f(doc, url); 137 | let elems, nextUrl; 138 | document.dispatchEvent(new MouseEvent('GM_AutoPagerizeNextPageDoc', { 139 | bubbles: true, 140 | relatedTarget: doc, 141 | })); 142 | try { 143 | for (const el of doc.getElementsByTagName('script')) 144 | el.remove(); 145 | elems = xpather.getElements(rule.pageElement, doc); 146 | nextUrl = getNextURL(rule.nextLink, doc, url); 147 | } catch (e) { 148 | statusShow({error: chrome.i18n.getMessage('errorExtractInfo')}); 149 | return; 150 | } 151 | if (elems.length) 152 | addPageElements(url, elems); 153 | loadedURLs[url] = 1; 154 | requestURL = nextUrl; 155 | statusShow({loading: false}); 156 | document.dispatchEvent(new Event('GM_AutoPagerizeNextPageLoaded', {bubbles: true})); 157 | if (!nextUrl) { 158 | terminate(); 159 | } else { 160 | return true; 161 | } 162 | } 163 | 164 | function addPageElements(url, elems) { 165 | if (insertPoint.ownerDocument !== document) { 166 | const el = xpather.getLast(rule.pageElement); 167 | if (el) insertPoint = ensureNextSibling(el); 168 | } 169 | const parent = insertPoint.parentNode; 170 | const bin = document.createDocumentFragment(); 171 | const p = $create('p', {className: 'autopagerize_page_info'}, [ 172 | chrome.i18n.getMessage('page') + ' ', 173 | $create('a', { 174 | href: url, 175 | className: 'autopagerize_link', 176 | textContent: ++pageNum, 177 | }), 178 | ]); 179 | if (elems[0].tagName !== 'TR') { 180 | bin.appendChild($create('hr', {className: 'autopagerize_page_separator'})); 181 | bin.appendChild(p); 182 | } else { 183 | let cols = 0; 184 | for (const sibling of parent.children) 185 | if (sibling.tagName === 'TD' || sibling.tagName === 'TH') 186 | cols += sibling.colSpan || 1; 187 | bin.appendChild( 188 | $create('tr', {}, 189 | $create('td', {colSpan: cols}, 190 | p))); 191 | } 192 | elems.forEach(bin.appendChild, bin); 193 | parent.insertBefore(bin, insertPoint); 194 | watchBottom(); 195 | } 196 | 197 | function watchBottom() { 198 | xo.disconnect(); 199 | xoElem = insertPoint.tagName ? insertPoint 200 | : insertPoint.previousElementSibling || insertPoint.parentNode; 201 | xo.observe(xoElem); 202 | } 203 | 204 | /** @param {IntersectionObserverEntry} e */ 205 | function onIntersect([e]) { 206 | if (e.isIntersecting) { 207 | xo.disconnect(); 208 | xoElem = null; 209 | request(); 210 | } 211 | } 212 | 213 | function terminate(e) { 214 | if (e && chrome.runtime.id) 215 | return; 216 | chrome.runtime.onMessage.removeListener(xpather.onmessage); 217 | removeEventListener(orphanMessageId, terminate); 218 | delete window.run; 219 | delete window.xpather; 220 | xo.disconnect(); 221 | xo = xoElem = null; 222 | statusRemove(1500); 223 | if (e) 224 | dispatchEvent(new Event(orphanMessageId + ':terminated')); 225 | } 226 | 227 | function doLoadMore(num) { 228 | if (num === 'query') 229 | return pagesRemaining; 230 | pagesRemaining = --num || 0; 231 | if (num >= 0 && request({force: true})) { 232 | onPageProcessed = ok => { 233 | if (ok) 234 | doLoadMore.timer = setTimeout(doLoadMore, requestInterval, num); 235 | chrome.runtime.connect({name: 'pagesRemaining:' + num}) 236 | .onDisconnect.addListener(() => chrome.runtime.lastError); 237 | }; 238 | } else { 239 | clearTimeout(doLoadMore.timer); 240 | onPageProcessed = null; 241 | } 242 | } 243 | 244 | function getNextURL(xpath, doc, url) { 245 | const next = xpather.getFirst(xpath, doc); 246 | if (next) { 247 | if (doc !== document && !doc.querySelector('base[href]')) 248 | doc.head.appendChild(doc.createElement('base')).href = url; 249 | if (!next.getAttribute('href')) 250 | next.setAttribute('href', next.getAttribute('action') || next.value); 251 | return next.href; 252 | } 253 | } 254 | 255 | function getStatusStyle(css = status.style) { 256 | // strip all '!important', collapse ;; into ; and ensure ; at the end 257 | return (css.replace(/[;\s]+$|!important/g, '').replace(/;{2,}/g, ';') + ';') 258 | .replace(/;/g, '!important;'); 259 | } 260 | 261 | function statusCreate() { 262 | if (status.element && document.contains(status.element)) 263 | return; 264 | const el = status.element = document.createElement('div'); 265 | el.id = 'autopagerize_message_bar'; 266 | el.textContent = chrome.i18n.getMessage('loading') + '...'; 267 | statusSetStyle('display: none'); 268 | document.body.appendChild(el); 269 | } 270 | 271 | function statusRemove(timeout) { 272 | clearTimeout(status.timer); 273 | if (timeout) 274 | status.timer = setTimeout(statusRemove, timeout); 275 | else if (status.element) { 276 | status.element.remove(); 277 | status.element = null; 278 | } 279 | } 280 | 281 | function statusSetStyle(extra = '', main = getStatusStyle()) { 282 | status.element.style.cssText = main + extra.replace(/;/g, '!important;'); 283 | } 284 | 285 | function statusShow({loading, error}) { 286 | let show; 287 | let style; 288 | if (loading !== undefined) { 289 | show = loading && status.enabled; 290 | if (show) 291 | statusCreate(); 292 | else if (!status.enabled) 293 | return; 294 | style = getStatusStyle(); 295 | 296 | } else if (error !== undefined) { 297 | show = true; 298 | statusCreate(); 299 | statusRemove(3000); 300 | style = getStatusStyle(status.styleError); 301 | status.element.textContent = `${chrome.i18n.getMessage('error')}: ${error}`; 302 | 303 | } else 304 | return; 305 | 306 | statusSetStyle(`opacity:0; ${show ? 'display:block' : ''}`, style); 307 | setTimeout(statusSetStyle, 308 | show ? 0 : parseFloat(status.element.style.transitionDuration) * 1000 || 0, 309 | `display: ${show ? 'block' : 'none'}`); 310 | } 311 | 312 | function $create(tag, props, children) { 313 | const el = document.createElementNS('http://www.w3.org/1999/xhtml', tag); 314 | if (props) 315 | Object.assign(el, props); 316 | if (children instanceof Node) 317 | el.appendChild(children); 318 | else if (Array.isArray(children)) 319 | el.append(...children); 320 | return el; 321 | } 322 | 323 | function loadSettings(ss) { 324 | let v; 325 | if ((v = ss.requestInterval * 1000)) 326 | requestInterval = v; 327 | if ((v = ss.pageHeightThreshold) || !xo) { 328 | xo?.disconnect(); 329 | xo = new IntersectionObserver(onIntersect, {rootMargin: v + 'px'}); 330 | if (xoElem) xo.observe(xoElem); 331 | } 332 | status.enabled = ss.showStatus !== false; 333 | if ((v = ss.statusStyle)) 334 | status.style = v; 335 | if ((v = ss.statusStyleError)) 336 | status.styleError = v; 337 | } 338 | })(); 339 | -------------------------------------------------------------------------------- /content/xpather.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | dispatchEvent(new Event(chrome.runtime.id)); 4 | window.xpather = { 5 | 6 | MICROFORMAT: { 7 | url: '.*', 8 | nextLink: '//a[@rel="next"] | //link[@rel="next"]', 9 | insertBefore: '//*[contains(@class, "autopagerize_insert_before")]', 10 | pageElement: '//*[contains(@class, "autopagerize_page_element")]', 11 | }, 12 | 13 | getMatchingRule(rules) { 14 | rules.push(xpather.MICROFORMAT); 15 | for (const r of rules) { 16 | if (xpather.getFirst(r.pageElement) && 17 | xpather.getFirst(r.nextLink)) 18 | return r; 19 | } 20 | }, 21 | 22 | /** 23 | * @param {string} expr 24 | * @param {Node} [node] 25 | * @return {(Node|Element)[]} 26 | */ 27 | getElements(expr, node) { 28 | const x = xpather.evaluate(expr, node, XPathResult.ORDERED_NODE_ITERATOR_TYPE); 29 | const nodes = []; 30 | for (let node; (node = x?.iterateNext());) 31 | nodes.push(node); 32 | return nodes; 33 | }, 34 | 35 | /** 36 | * @param {string} expr 37 | * @param {Node} [node] 38 | * @return {?Node|Element} 39 | */ 40 | getFirst(expr, node) { 41 | return xpather.evaluate(expr, node, XPathResult.FIRST_ORDERED_NODE_TYPE)?.singleNodeValue; 42 | }, 43 | 44 | /** 45 | * @param {string} expr 46 | * @param {Node} [node] 47 | * @return {?Node|Element} 48 | */ 49 | getLast(expr, node) { 50 | return xpather.getFirst(`(${expr})[last()]`, node); 51 | }, 52 | 53 | evaluate(expr, node = document, resultType) { 54 | const doc = node.ownerDocument || node; 55 | const defaultNS = node.lookupNamespaceURI(null); 56 | let resolver = doc.createNSResolver(node.documentElement || node); 57 | 58 | if (defaultNS) { 59 | const defaultPrefix = '__default__'; 60 | const defaultResolver = resolver; 61 | expr = xpather.addDefaultPrefix(expr, defaultPrefix); 62 | resolver = prefix => 63 | prefix === defaultPrefix ? 64 | defaultNS : 65 | defaultResolver.lookupNamespaceURI(prefix); 66 | } 67 | try { 68 | return doc.evaluate(expr, node, resolver, resultType, null); 69 | } catch (e) { 70 | console.debug(e); 71 | } 72 | }, 73 | 74 | TOKEN_PATTERN: RegExp( 75 | [ 76 | /([A-Za-z_\u00c0-\ufffd][\w\-.\u00b7-\ufffd]*|\*)\s*(::?|\()?/, 77 | /(".*?"|'.*?'|\d+(?:\.\d*)?|\.(?:\.|\d+)?|[)\]])/, 78 | /(\/\/?|!=|[<>]=?|[([|,=+-])/, 79 | /([@$])/, 80 | ].map(rx => rx.source).join('|'), 81 | 'g' 82 | ), 83 | 84 | addDefaultPrefix(expr, prefix) { 85 | const TERM = 1; 86 | const OPERATOR = 2; 87 | const MODIFIER = 3; 88 | let tokenType = OPERATOR; 89 | prefix += ':'; 90 | return expr.replace(xpather.TOKEN_PATTERN, (token, id, suffix, term, operator) => { 91 | if (suffix) { 92 | tokenType = 93 | suffix === ':' || 94 | suffix === '::' && (id === 'attribute' || id === 'namespace') ? 95 | MODIFIER : 96 | OPERATOR; 97 | } else if (id) { 98 | if (tokenType === OPERATOR && id !== '*') 99 | token = prefix + token; 100 | tokenType = tokenType === TERM ? OPERATOR : TERM; 101 | } else { 102 | tokenType = 103 | term ? TERM : 104 | operator ? OPERATOR : 105 | MODIFIER; 106 | } 107 | return token; 108 | }); 109 | }, 110 | 111 | onmessage([cmd, arg, arg2], sender, sendResponse) { 112 | let res; 113 | switch (cmd) { 114 | 115 | case 'checkOrphan': { 116 | const id = chrome.runtime.id; 117 | const idCheck = id + ':terminated'; 118 | const orphanTerminated = () => (res = true); 119 | addEventListener(idCheck, orphanTerminated); 120 | dispatchEvent(new Event(id)); 121 | removeEventListener(idCheck, orphanTerminated); 122 | break; 123 | } 124 | 125 | case 'checkRules': 126 | res = self.xpather?.getMatchingRule; 127 | if ((xpather.launch = res && (res = res(arg)) && [arg, res])) 128 | res = {run: typeof run === 'function'}; 129 | break; 130 | 131 | case 'launch': 132 | if (typeof run !== 'function') 133 | break; 134 | if (!arg2) 135 | self.dispatchEvent(new Event(chrome.runtime.id)); 136 | run({[cmd]: xpather[cmd], settings: arg}); 137 | xpather[cmd] = null; 138 | self.launched = 1; 139 | break; 140 | 141 | case 'launched': 142 | res = self[cmd] === 1; 143 | delete self[cmd]; 144 | 145 | // fallthrough 146 | case 'run': 147 | if (typeof run === 'function') 148 | run(arg); 149 | break; 150 | } 151 | sendResponse(res ?? null); 152 | }, 153 | }; 154 | 155 | chrome.runtime.onMessage.addListener(xpather.onmessage); 156 | -------------------------------------------------------------------------------- /icons/128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/128.png -------------------------------------------------------------------------------- /icons/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/16.png -------------------------------------------------------------------------------- /icons/32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/32.png -------------------------------------------------------------------------------- /icons/48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/48.png -------------------------------------------------------------------------------- /icons/off/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/off/16.png -------------------------------------------------------------------------------- /icons/off/32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/off/32.png -------------------------------------------------------------------------------- /icons/off/48.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tophf/autopagerize/f745b38cd9b943f83a9ef78da43a183a6c91b6f6/icons/off/48.png -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 3, 3 | "version": "2.0.5", 4 | "minimum_chrome_version": "120", 5 | "name": "AutoPagerize", 6 | "description": "__MSG_description__", 7 | "homepage_url": "https://github.com/tophf/autopagerize", 8 | "default_locale": "en", 9 | "background": { 10 | "service_worker": "bg/bg.js", 11 | "type": "module" 12 | }, 13 | "icons": { 14 | "16": "icons/16.png", 15 | "32": "icons/32.png", 16 | "48": "icons/48.png", 17 | "128": "icons/128.png" 18 | }, 19 | "options_ui": { 20 | "page": "ui/options.html" 21 | }, 22 | "action": { 23 | "default_popup": "ui/popup.html?fail", 24 | "default_icon": { 25 | "16": "icons/off/16.png", 26 | "32": "icons/off/32.png", 27 | "48": "icons/off/48.png" 28 | } 29 | }, 30 | "commands": { 31 | "_execute_action": {}, 32 | "onOff": { 33 | "description": "__MSG_onOff__" 34 | }, 35 | "loadMore01": { 36 | "description": "__MSG_loadMore__ (1)" 37 | }, 38 | "loadMore02": { 39 | "description": "__MSG_loadMore__ (2)" 40 | }, 41 | "loadMore05": { 42 | "description": "__MSG_loadMore__ (5)" 43 | }, 44 | "loadMore10": { 45 | "description": "__MSG_loadMore__ (10)" 46 | }, 47 | "loadMore20": { 48 | "description": "__MSG_loadMore__ (20)" 49 | }, 50 | "loadMore50": { 51 | "description": "__MSG_loadMore__ (50)" 52 | } 53 | }, 54 | "permissions": [ 55 | "alarms", 56 | "contextMenus", 57 | "offscreen", 58 | "scripting", 59 | "storage", 60 | "tabs", 61 | "webNavigation" 62 | ], 63 | "host_permissions": [ 64 | "" 65 | ], 66 | "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu7D4uoQ0hsOZMY5sdv66oBA6Cy7SUWUVb80TQs6wUTv6kGTqRMB+hzW2AHHzxiYpmzIq0tpwUsb5NQpMAvmO/4tSiFXRgyesR3TaITWM7B9FDcHUAAnlOgBHM08MnjO6Ur4dR3djfJKpXKMAvygcU0yrlnSarUg7vkXH+36OTDqOWuG07lyBszYbRDTSYOSSaApXTb736mSjxshM4n77ToB+n4x+v+GuVaIWcu1No2YA7NTatCg8Nt3sF+dP/ZiBglJ0Bo5/1P1A/0OzsC6CpKpqOmmSGGIjWJDf39W3ZFgTrZoPxn3Swkaub0qLgZwVa+94Yax+FbTmkJtGdQ2XiwIDAQAB" 67 | } 68 | -------------------------------------------------------------------------------- /siteinfo-updater.js: -------------------------------------------------------------------------------- 1 | /* eslint-env node */ 2 | 'use strict'; 3 | 4 | const http = require('http'); 5 | const fs = require('fs'); 6 | 7 | const DATA_URL = 'http://wedata.net/databases/AutoPagerize/items_all.json'; 8 | const FILE = 'siteinfo.json'; 9 | const KNOWN_KEYS = [ 10 | 'url', 11 | 'nextLink', 12 | 'insertBefore', 13 | 'pageElement', 14 | ]; 15 | 16 | console.log('Fetching ' + DATA_URL); 17 | http.get(DATA_URL, r => { 18 | const data = []; 19 | let size = 0; 20 | r.on('data', str => { 21 | data.push(str); 22 | size += str.length; 23 | process.stdout.write('\r' + Math.round(size / 1024) + ' kiB'); 24 | }); 25 | r.on('end', () => { 26 | const json = sanitize(JSON.parse(data.join(''))); 27 | fs.writeFileSync(FILE, JSON.stringify(json, null, ' ')); 28 | console.log(); 29 | console.log('Done'); 30 | }); 31 | }); 32 | 33 | function sanitize(data) { 34 | return (Array.isArray(data) ? data : []) 35 | .map(x => x && x.data && x.data.url && pickKnownKeys(x.data, x.resource_url)) 36 | .filter(Boolean) 37 | .sort((a, b) => a.id - b.id); 38 | } 39 | 40 | function pickKnownKeys(entry, resourceUrl) { 41 | for (const key of Object.keys(entry)) { 42 | if (!KNOWN_KEYS.includes(key)) { 43 | const newEntry = {}; 44 | for (const k of KNOWN_KEYS) { 45 | const v = entry[k]; 46 | if (v !== undefined) 47 | newEntry[k] = v; 48 | } 49 | entry = newEntry; 50 | break; 51 | } 52 | } 53 | entry.id = Number(resourceUrl.slice(resourceUrl.lastIndexOf('/') + 1)); 54 | return entry; 55 | } 56 | -------------------------------------------------------------------------------- /ui/options-backup.js: -------------------------------------------------------------------------------- 1 | import {arrayOrDummy, DEFAULTS, inBG} from '/util/common.js'; 2 | import {$} from '/util/dom.js'; 3 | import {loadRules} from './options-rules.js'; 4 | import {collectSettings, renderSettings} from './options.js'; 5 | 6 | $('#btnImport').onclick = importSettings; 7 | $('#btnExport').onclick = exportSettings; 8 | $('#importExportTitle').onclick = e => 9 | setTimeout(() => e.target.parentElement.scrollIntoView({behavior: 'smooth'})); 10 | 11 | async function importSettings() { 12 | let imported; 13 | const elError = $('#importError'); 14 | try { 15 | imported = JSON.parse($('#backup').value); 16 | elError.hidden = true; 17 | } catch (e) { 18 | elError.textContent = String(e); 19 | elError.hidden = false; 20 | return; 21 | } 22 | const ovr = $('#overwriteSettings').checked; 23 | const settings = ovr ? {...DEFAULTS} : collectSettings(); 24 | for (const [k, ref] of Object.entries(DEFAULTS)) { 25 | const v = imported[k]; 26 | if (v === undefined) { 27 | if (ovr) 28 | settings[k] = Array.isArray(ref) ? [...ref] : ref; 29 | continue; 30 | } 31 | settings[k] = 32 | ref === true || ref === false ? Boolean(v) : 33 | typeof ref === 'string' ? String(v || '') : 34 | typeof ref === 'number' ? isNaN(v) ? ref : +v : 35 | Array.isArray(ref) ? deduplicate(settings, k, v) : 36 | v; 37 | } 38 | await inBG.writeSettings(settings); 39 | $('#rules').textContent = ''; 40 | loadRules(settings.rules); 41 | renderSettings(settings, {force: true}); 42 | } 43 | 44 | function exportSettings() { 45 | const elBackup = $('#backup'); 46 | elBackup.focus(); 47 | elBackup.value = JSON.stringify(collectSettings(), null, ' '); 48 | elBackup.select(); 49 | document.execCommand('copy'); 50 | $('#importError').hidden = true; 51 | } 52 | 53 | function deduplicate(settings, k, v) { 54 | return [...new Set([...settings[k], ...arrayOrDummy(v)])]; 55 | } 56 | -------------------------------------------------------------------------------- /ui/options-dark.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #222; 3 | color: #999; 4 | } 5 | code, 6 | .desc pre, 7 | #size, 8 | #date { 9 | color: darkseagreen; 10 | } 11 | a { 12 | color: deepskyblue; 13 | } 14 | a:visited { 15 | color: mediumpurple; 16 | } 17 | button { 18 | background: linear-gradient(-10deg, #333, #555); 19 | border: 1px solid #181818; 20 | border-radius: 3px; 21 | color: #eee; 22 | padding: .4em 1em .35em; 23 | box-shadow: 1px 1px 3px #0003; 24 | } 25 | summary { 26 | color: #bbb; 27 | } 28 | input[type="text"], 29 | input[type="number"], 30 | textarea { 31 | color: #aaa; 32 | background-color: #181818; 33 | border-color: #333; 34 | } 35 | textarea:focus { 36 | color: #ddd; 37 | } 38 | .rule:not(:last-child) { 39 | border-bottom-color: #444; 40 | } 41 | -------------------------------------------------------------------------------- /ui/options-rules.js: -------------------------------------------------------------------------------- 1 | export { 2 | collectRules, 3 | loadRules, 4 | resizeArea, 5 | rulesEqual, 6 | }; 7 | 8 | import {arrayOrDummy} from '/util/common.js'; 9 | import {$, $$} from '/util/dom.js'; 10 | import {i18n} from '/util/locale.js'; 11 | 12 | const DUMMY_RULE = {url: '^https?://www\\.'}; 13 | let defaultAreaHeight; 14 | 15 | function loadRules(rules) { 16 | 17 | const rulesContainer = $('#rules'); 18 | rulesContainer.addEventListener('focusin', resizeArea); 19 | rulesContainer.addEventListener('focusout', resizeArea); 20 | rulesContainer.addEventListener('input', resizeArea); 21 | rulesContainer.addEventListener('input', onInput); 22 | rulesContainer.addEventListener('click', onClick); 23 | 24 | rules = arrayOrDummy(rules); 25 | const bin = addRules(rules.length ? rules : [DUMMY_RULE]); 26 | if (bin.firstChild) { 27 | rulesContainer.appendChild(bin); 28 | rulesContainer.closest('details').open = true; 29 | } 30 | 31 | } 32 | 33 | function collectRules(elements) { 34 | const rules = []; 35 | for (const r of elements || $$('#rules .rule')) { 36 | if (r.classList.contains('deleted')) 37 | continue; 38 | const rule = {}; 39 | let isDummy = true; 40 | for (const m of $$('.rule-member', r)) { 41 | const el = $('textarea', m); 42 | const value = el.value.trim(); 43 | const v = el._data.savedValue = value; 44 | if (!v) 45 | continue; 46 | if (isDummy && v !== (DUMMY_RULE[el.dataset.type] || '')) 47 | isDummy = false; 48 | rule[$('.rule-member-name', m).textContent] = v; 49 | } 50 | if (!isDummy) 51 | rules.push(rule); 52 | } 53 | return rules; 54 | } 55 | 56 | function addRules(rules) { 57 | const bin = document.createDocumentFragment(); 58 | const tplRule = $('#tplRule').content.firstElementChild; 59 | const tplMember = $('#tplRuleMember').content.firstElementChild; 60 | const memberName = $('.rule-member-name', tplMember).firstChild; 61 | const memberTitle = memberName.parentNode.attributes.title; 62 | const KEYS = ['url', 'pageElement', 'nextLink', 'insertBefore']; 63 | let clone; 64 | for (const rule of rules) { 65 | if (rule) { 66 | const el = tplRule.cloneNode(true); 67 | el._data = {savedValue: false}; 68 | for (const k of KEYS) { 69 | memberName.nodeValue = k; 70 | memberTitle.nodeValue = k; 71 | clone = tplMember.cloneNode(true); 72 | const area = clone.getElementsByTagName('textarea')[0]; 73 | const v = rule[k] || ''; 74 | area._data = {}; 75 | area.value = area._data.savedValue = v; 76 | area.dataset.type = k; 77 | if (!v) 78 | area.classList.add('empty'); 79 | if (k === 'insertBefore') 80 | area.required = false; 81 | el.appendChild(clone); 82 | } 83 | bin.appendChild(el); 84 | } 85 | } 86 | return bin; 87 | } 88 | 89 | function resizeArea(e) { 90 | const el = e.target; 91 | if (el.localName !== 'textarea') 92 | return; 93 | if (!defaultAreaHeight) 94 | defaultAreaHeight = el.offsetHeight; 95 | switch (e.type) { 96 | case 'focusin': { 97 | const sh = el.scrollHeight; 98 | if (sh > defaultAreaHeight * 1.5) 99 | el.style.height = sh + 'px'; 100 | break; 101 | } 102 | case 'focusout': { 103 | if (el.style.height) 104 | el.style.height = ''; 105 | break; 106 | } 107 | case 'input': { 108 | const sh = el.scrollHeight; 109 | const oh = el.offsetHeight; 110 | if (sh > oh + defaultAreaHeight / 2 || sh < oh) 111 | el.style.height = sh > defaultAreaHeight ? sh + 'px' : ''; 112 | break; 113 | } 114 | } 115 | } 116 | 117 | function validateArea(el) { 118 | const v = el.value.trim(); 119 | let error = ''; 120 | if (v) { 121 | try { 122 | if (el.dataset.type === 'url') 123 | RegExp(v); 124 | else 125 | document.evaluate(v, document, null, XPathResult.ANY_TYPE, null); 126 | } catch (e) { 127 | error = String(e); 128 | const i = (error.indexOf(`'${v}'`) + 1) || (error.indexOf(`/${v}/`) + 1); 129 | if (i > 0) 130 | error = error.slice(i + v.length + 2).replace(/^[\s:]*(is\s)?|\.$/g, ''); 131 | } 132 | } else if (el.required) { 133 | error = i18n('errorEmptyValue'); 134 | } 135 | el.setCustomValidity(error); 136 | el.classList.toggle('empty', !v); 137 | el.title = error; 138 | } 139 | 140 | function onInput({target: el}) { 141 | if (el.localName === 'textarea') 142 | validateArea(el); 143 | } 144 | 145 | function addRule(base) { 146 | base.after(addRules([DUMMY_RULE])); 147 | } 148 | 149 | function deleteRule(base) { 150 | base.classList.toggle('deleted'); 151 | base.value = !base.value; 152 | const isDisposable = base.value && 153 | $('#rules').children[1] && 154 | rulesEqual(collectRules([base]), [DUMMY_RULE]); 155 | if (isDisposable) 156 | base.value = base._data.savedValue = 'canDelete'; 157 | base.dispatchEvent(new Event('change', {bubbles: true})); 158 | if (base.value === 'canDelete') 159 | base.remove(); 160 | else 161 | $('[data-action="delete"]', base).textContent = 162 | i18n(base.value ? 'restore' : 'delete'); 163 | } 164 | 165 | function onClick(e) { 166 | if (e.defaultPrevented) 167 | return; 168 | const {action} = e.target.dataset; 169 | if (action) { 170 | e.preventDefault(); 171 | const fn = action === 'add' ? addRule : deleteRule; 172 | fn(e.target.closest('.rule')); 173 | } 174 | } 175 | 176 | function rulesEqual(arrayA, arrayB) { 177 | arrayA = arrayOrDummy(arrayA); 178 | arrayB = arrayOrDummy(arrayB); 179 | if (arrayA.length !== arrayB.length) 180 | return; 181 | for (let i = 0; i < arrayA.length; i++) { 182 | const a = arrayA[i]; 183 | const b = arrayB[i]; 184 | if (!a || !b) 185 | return; 186 | for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) { 187 | if (a[k] !== b[k]) 188 | return; 189 | } 190 | } 191 | return true; 192 | } 193 | -------------------------------------------------------------------------------- /ui/options.css: -------------------------------------------------------------------------------- 1 | body { 2 | font: normal 100%/1.25 sans-serif; 3 | padding: 0 1em 1em; 4 | min-width: 500px; 5 | } 6 | #btnSaveWrapper { 7 | background-color: #ffd700a0; 8 | position: fixed; 9 | top: 0; 10 | right: 0; 11 | padding: 1em; 12 | border: 1px solid burlywood; 13 | } 14 | #btnSaveWrapper div { 15 | font-size: smaller; 16 | } 17 | #btnSave { 18 | font-weight: bold; 19 | } 20 | section:nth-child(n + 2) { 21 | margin-top: 1em; 22 | } 23 | summary { 24 | cursor: pointer; 25 | font-weight: bold; 26 | margin-bottom: .5em; 27 | } 28 | .desc { 29 | margin: 1em; 30 | font-size: 75%; 31 | } 32 | .desc summary { 33 | font-weight: normal; 34 | } 35 | code, 36 | .desc pre { 37 | font-weight: bold; 38 | color: darkgreen; 39 | } 40 | table { 41 | border-spacing: 0; 42 | } 43 | textarea { 44 | width: 100%; 45 | box-sizing: border-box; 46 | resize: vertical; 47 | border: 1px solid #8883; 48 | background-color: #8882; 49 | } 50 | #rules { 51 | counter-reset: rule; 52 | } 53 | .rule { 54 | position: relative; 55 | } 56 | .rule:not(:last-child) { 57 | padding-bottom: 1em; 58 | margin-bottom: 1em; 59 | border-bottom: 3px double lightgray; 60 | } 61 | .rule.deleted { 62 | padding-top: 1em; 63 | border: .5em solid transparent; 64 | } 65 | .rule:not(.deleted)::before { 66 | counter-increment: rule; 67 | content: "Rule " counter(rule); 68 | display: block; 69 | font-weight: bold; 70 | font-size: 60%; 71 | margin-bottom: .25rem; 72 | color: seagreen; 73 | } 74 | .rule-actions { 75 | position: absolute; 76 | right: 0; 77 | top: -.5em; 78 | text-align: right; 79 | } 80 | .rule-action { 81 | padding: 0 1em 1px; 82 | border-radius: 5px; 83 | opacity: .5; 84 | font-weight: bold; 85 | font-size: .7rem; 86 | cursor: pointer; 87 | user-select: none; 88 | } 89 | .rule-action[data-action="add"] { 90 | background-color: #bcd6bc; 91 | border: 1px solid seagreen; 92 | color: #165431; 93 | } 94 | .rule-action[data-action="delete"] { 95 | background-color: #ccc; 96 | border: 1px solid #888; 97 | color: #444; 98 | } 99 | .rule-action:hover { 100 | opacity: 1; 101 | } 102 | .deleted .rule-member { 103 | opacity: .25; 104 | } 105 | .rule-member { 106 | display: flex; 107 | align-items: center; 108 | } 109 | .rule-member-name { 110 | font-weight: bold; 111 | font-size: .6rem; 112 | width: 2.5rem; 113 | white-space: nowrap; 114 | overflow: hidden; 115 | text-overflow: ellipsis; 116 | color: darkseagreen; 117 | } 118 | .rule-member-value { 119 | margin-top: 2px; 120 | } 121 | :invalid { 122 | background-color: #f003; 123 | border: 1px solid #f008; 124 | } 125 | .empty[required] { 126 | background-color: #f001; 127 | border: 1px solid #f004; 128 | } 129 | .changed { 130 | box-shadow: 0 0 0 1px gold; 131 | } 132 | section:last-of-type details:not([open]) summary { 133 | margin-bottom: 0; 134 | } 135 | #backup { 136 | margin-top: .5em; 137 | } 138 | #importWrapper { 139 | border: none; 140 | padding: 0; 141 | margin: 0; 142 | } 143 | #importWrapper:disabled span { 144 | opacity: .5; 145 | } 146 | #importError { 147 | color: red; 148 | font-size: smaller; 149 | font-family: monospace; 150 | } 151 | #size, #date { 152 | color: seagreen; 153 | } 154 | #toggles label { 155 | display: flex; 156 | align-items: start; 157 | margin-top: .25rem; 158 | margin-bottom: .25rem; 159 | } 160 | #toggles label input { 161 | margin-right: .5em; 162 | } 163 | input[type="number"] { 164 | width: 4em; 165 | margin-left: .25em; 166 | } 167 | #toggles small { 168 | display: block; 169 | margin: .25em 0; 170 | } 171 | #styles label { 172 | display: flex; 173 | } 174 | #styles label span { 175 | min-width: 5em; 176 | } 177 | -------------------------------------------------------------------------------- /ui/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 22 | 23 | 35 | 36 | 37 | 38 |
39 | 42 | 45 | 52 | 56 | 63 |
64 | 65 |
66 | 71 |
72 | 73 |
74 |
75 | excludedPages 76 |
77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 |
example (singleURL):http://www.example.com/foo
example (wildcard):http://*.example.com/bar*
example (regexp):/[^.]+\.example\.com\//
92 |
93 |
94 |
95 | 96 |
97 |
98 | customRules 99 |
100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 118 | 119 | 120 |
example
URL, regexp^https://github\.com/[^/]+/[^/]+/(?:issues|pulls)
pageElement, XPath//div[starts-with(@id,'issue_')]
nextLink, XPath//a[@class='next_page']
insertBefore, 116 | XPath 117 | //footer optionalRare
121 |
122 |
123 | 124 |
125 |
126 | statusStyle 127 |
128 | 132 | 136 | statusStyleInfo 137 |
138 |
139 |
140 | 141 |
142 |
143 | siteinfo 144 |
145 |
size:
146 |
date:
147 | 148 |
149 |
150 |
151 | 152 |
153 |
154 | 155 | import / export 156 | 157 |
158 | 159 | 160 |
161 | 162 | 163 | 164 |
165 |
166 |
167 |
168 | 169 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /ui/options.js: -------------------------------------------------------------------------------- 1 | export { 2 | collectSettings, 3 | renderSettings, 4 | }; 5 | 6 | import {arrayOrDummy, DEFAULTS, loadSettings, inBG} from '/util/common.js'; 7 | import {$, $$} from '/util/dom.js'; 8 | import {dbExec} from '/util/storage-idb.js'; 9 | import {collectRules, loadRules, resizeArea} from './options-rules.js'; 10 | 11 | const ValueTransform = { 12 | // params: (value, element) 13 | render: { 14 | showStatus: v => v !== false, 15 | statusStyle: (v, el) => { 16 | const defaultValue = DEFAULTS[el._data.name]; 17 | el.placeholder = defaultValue; 18 | el.closest('details').open |= Boolean(v); 19 | el.addEventListener('focusin', resizeArea); 20 | el.addEventListener('focusout', resizeArea); 21 | el.addEventListener('input', resizeArea); 22 | return v || defaultValue; 23 | }, 24 | statusStyleError: (...args) => ValueTransform.render.statusStyle(...args), 25 | $array: (v, el) => { 26 | // set rows if first time init 27 | if (el._data.savedValue === undefined) 28 | el.rows = Math.max(2, Math.min(20, arrayOrDummy(v).length + 1)); 29 | return arrayOrDummy(v).join('\n').trim(); 30 | }, 31 | $boolean: v => v === true, 32 | $any: (v, el) => String(v !== undefined ? v : DEFAULTS[el._data.name]), 33 | }, 34 | // params: (element) 35 | parse: { 36 | rules: () => collectRules(), 37 | $array: el => el.value.trim().split(/\s+/), 38 | $boolean: el => el.checked, 39 | $number: el => el.valueAsNumber || DEFAULTS[el._data.name], 40 | $string: el => el.value !== DEFAULTS[el._data.name] ? el.value : '', 41 | }, 42 | find: (transforms, name, defaultValue) => 43 | transforms[name] || 44 | transforms[`$${Array.isArray(defaultValue) ? 'array' : typeof defaultValue}`] || 45 | transforms.$any, 46 | }; 47 | 48 | const changedElements = new Set(); 49 | 50 | loadSettings().then(settings => { 51 | renderSettings(settings); 52 | loadRules(settings.rules); 53 | 54 | $('#btnSave').onclick = save; 55 | $('#btnUpdate').onclick = update; 56 | $('#backup').oninput = ({target: el}) => ($('#importWrapper').disabled = !el.value.trim()); 57 | addEventListener('input', onChange, {passive: true}); 58 | addEventListener('change', onChange, {passive: true}); 59 | 60 | Promise.all([ 61 | dbExec.count(), 62 | dbExec({store: 'data'}).get('cacheDate'), 63 | ]).then(res => renderSiteinfoStats(...res)); 64 | }); 65 | 66 | function renderSettings(ss, {force} = {}) { 67 | for (const [k, defaultValue] of Object.entries(DEFAULTS)) { 68 | const el = document.getElementById(k); 69 | if (!el) 70 | continue; 71 | const firstInit = !el._data; 72 | // el._data.name is used when transforming so it should be defined beforehand 73 | if (firstInit) 74 | el._data = {name: k}; 75 | const v = ss[k] !== undefined ? ss[k] : defaultValue; 76 | const renderedValue = ValueTransform.find(ValueTransform.render, k, defaultValue)(v, el); 77 | if (firstInit || force) 78 | el[el.type === 'checkbox' ? 'checked' : 'value'] = renderedValue; 79 | el._data.savedValue = renderedValue; 80 | } 81 | } 82 | 83 | function renderSiteinfoStats(numRules, date) { 84 | $('#size').textContent = numRules; 85 | if (!+date) date = ''; 86 | const elDate = $('#date'); 87 | elDate.dateTime = date; 88 | elDate.textContent = date ? renderDate(date) : 'N/A'; 89 | elDate.title = date && date.toLocaleString(); 90 | } 91 | 92 | function renderDate(date) { 93 | if (Intl.RelativeTimeFormat) { 94 | let delta = (date - Date.now()) / 1000; 95 | for (const [span, unit] of [ 96 | [60, 'second'], 97 | [60, 'minute'], 98 | [24, 'hour'], 99 | [7, 'day'], 100 | [4, 'week'], 101 | [12, 'month'], 102 | [1e99, 'year'], 103 | ]) { 104 | if (Math.abs(delta) < span) 105 | return new Intl.RelativeTimeFormat({style: 'short'}).format(Math.round(delta), unit); 106 | delta /= span; 107 | } 108 | } 109 | return date.toLocaleString(); 110 | } 111 | 112 | async function save() { 113 | const ss = collectSettings(); 114 | inBG.writeSettings(ss); 115 | renderSettings(ss); 116 | changedElements.forEach(el => el.classList.remove('changed')); 117 | changedElements.clear(); 118 | for (const el of $$('#rules .deleted')) 119 | el._data.savedValue = !el._data.savedValue; 120 | 121 | $('#btnSaveWrapper').hidden = true; 122 | } 123 | 124 | async function update() { 125 | const btn = $('#btnUpdate'); 126 | const label = btn.textContent; 127 | btn.disabled = true; 128 | 129 | chrome.runtime.onConnect.addListener(displayProgress); 130 | const portName = performance.now() + '.' + Math.random(); 131 | const numRules = await inBG.updateSiteinfo(portName); 132 | chrome.runtime.onConnect.removeListener(displayProgress); 133 | 134 | renderSiteinfoStats(numRules, numRules > 0 ? new Date() : null); 135 | btn.textContent = label; 136 | btn.disabled = false; 137 | 138 | function displayProgress(port) { 139 | if (port.name === portName) 140 | port.onMessage.addListener(loaded => { 141 | btn.textContent = (loaded / 1024).toFixed(0) + ' kiB'; 142 | }); 143 | } 144 | } 145 | 146 | function collectSettings() { 147 | const ss = {}; 148 | for (const [k, defaultValue] of Object.entries(DEFAULTS)) { 149 | const el = document.getElementById(k); 150 | if (el) 151 | ss[k] = ValueTransform.find(ValueTransform.parse, k, defaultValue)(el); 152 | } 153 | return ss; 154 | } 155 | 156 | function onChange({target: el}) { 157 | if (el.closest('.ignore-changes')) 158 | return; 159 | const value = el[el.type === 'checkbox' ? 'checked' : 'value']; 160 | const changed = value !== el._data.savedValue; 161 | if (changed) 162 | changedElements.add(el); 163 | else 164 | changedElements.delete(el); 165 | if (changed !== el.classList.contains('changed')) 166 | el.classList.toggle('changed', changed); 167 | const unsalvageable = !changedElements.size || (el.checkValidity && !el.checkValidity()); 168 | const btn = $('#btnSaveWrapper'); 169 | if (btn.hidden !== unsalvageable) 170 | btn.hidden = unsalvageable; 171 | } 172 | -------------------------------------------------------------------------------- /ui/popup-dark.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #333; 3 | color: #aaa; 4 | } 5 | a { 6 | color: skyblue; 7 | } 8 | select { 9 | color: #bbb; 10 | background-color: #222; 11 | border-color: #111; 12 | } 13 | section[data-status="true"] { 14 | background-color: seagreen; 15 | color: #fff; 16 | } 17 | section[data-status="false"] { 18 | background-color: #555; 19 | color: #fff; 20 | } 21 | section:nth-child(n + 3) { 22 | border-color: #222; 23 | } 24 | button { 25 | background: linear-gradient(-15deg, #333, #666); 26 | border: 1px solid #000; 27 | color: #eee; 28 | } 29 | #failure { 30 | color: #caa794; 31 | background-color: #f802; 32 | } 33 | -------------------------------------------------------------------------------- /ui/popup-exclude.js: -------------------------------------------------------------------------------- 1 | export { 2 | applyPerSite, 3 | updateSpecificity, 4 | }; 5 | 6 | import {arrayOrDummy, inBG, loadSettings, tabSend} from '/util/common.js'; 7 | import {$, $$} from '/util/dom.js'; 8 | import * as popup from './popup.js'; 9 | 10 | $('#excludeSection').addEventListener('click', updateSpecificity, {once: true}); 11 | 12 | async function exclude(e) { 13 | e.preventDefault(); 14 | 15 | const pattern = e.target.url; 16 | await applyPerSite(pattern); 17 | 18 | let path = chrome.runtime.getManifest().action.default_popup; 19 | if (!path.startsWith('/')) 20 | path = '/' + path; 21 | 22 | for (const t of await findExcludedTabs(pattern)) { 23 | await Promise.all([ 24 | inBG.setIcon({tabId: t.id, type: 'off'}), 25 | chrome.action.setPopup({tabId: t.id, popup: path}), 26 | !t.discarded && tabSend(t.id, ['run', {terminate: true}]), 27 | ]); 28 | } 29 | 30 | location.assign(path); 31 | } 32 | 33 | async function applyPerSite(pattern, listType = 'exclusions') { 34 | const list = arrayOrDummy(await loadSettings(listType)); 35 | if (!list.includes(pattern)) { 36 | list.push(pattern); 37 | inBG.writeSettings({[listType]: list}); 38 | } 39 | } 40 | 41 | function updateSpecificity() { 42 | const {url} = popup.tab; 43 | for (const el of $$('#specificity a')) { 44 | const {type} = el.dataset; 45 | el.title = decodeURIComponent(el.url = 46 | type === 'url' ? url : 47 | type === 'prefix' ? url + '*' : 48 | type === 'domain' ? new URL(url).origin + '/*' : '' 49 | ); 50 | el.onclick = exclude; 51 | } 52 | $('#specificity').dataset.ready = ''; 53 | } 54 | 55 | async function findExcludedTabs(pattern) { 56 | const isPrefix = pattern.endsWith('*'); 57 | const url = isPrefix ? pattern.slice(0, -1) : pattern; 58 | // the API can't query #hash and may return tabs with a #different-hash 59 | // so we need to get all tabs with the same base URL and then filter the results 60 | const hashlessUrl = pattern.split('#', 1)[0] + (isPrefix ? '*' : ''); 61 | const tabs = await chrome.tabs.query({url: hashlessUrl}); 62 | return tabs.filter(t => isPrefix ? t.url.startsWith(url) : t.url === url); 63 | } 64 | -------------------------------------------------------------------------------- /ui/popup-fail-detect.js: -------------------------------------------------------------------------------- 1 | /** Not a module to ensure it runs as early as possible */ 2 | 'use strict'; 3 | 4 | if (location.search) (async () => { 5 | document.documentElement.classList.add('failed-page'); 6 | const [{url, id: tabId}] = await chrome.tabs.query({active: true, currentWindow: true}); 7 | if (await chrome.tabs.sendMessage(tabId, ['checkOrphan'], {frameId: 0}).catch(() => 0)) { 8 | await chrome.runtime.sendMessage({action: 'reinject', data: {tabId, url}}); 9 | location.search = ''; 10 | } 11 | })(); 12 | -------------------------------------------------------------------------------- /ui/popup-generic-rules.js: -------------------------------------------------------------------------------- 1 | import {doDelay, ignoreLastError, RETRY_TIMEOUT} from '/util/common.js'; 2 | import {$} from '/util/dom.js'; 3 | import {applyPerSite, updateSpecificity} from './popup-exclude.js'; 4 | import * as popup from './popup.js'; 5 | 6 | $('#genericRulesSection').hidden = false; 7 | $('#genericRulesSection').addEventListener('click', async () => { 8 | const GRE = 'genericRulesEnabled'; 9 | if ((await chrome.storage.sync.get(GRE))[GRE]) { 10 | $('#genericRulesSection').removeAttribute('disabled'); 11 | if (!$('#specificity').dataset.ready) 12 | updateSpecificity(); 13 | $('#grSlot').replaceWith(Object.assign($('#specificity').cloneNode(true), { 14 | id: '', 15 | async onclick(e) { 16 | e.preventDefault(); 17 | const tabId = popup.tab.id; 18 | await applyPerSite(e.target.title, 'genericSites'); 19 | chrome.tabs.reload(tabId, ignoreLastError); 20 | await waitForTabLoad(popup.tab); 21 | await doDelay(RETRY_TIMEOUT); 22 | location.search = ''; 23 | }, 24 | })); 25 | } 26 | }, {once: true}); 27 | 28 | function waitForTabLoad(tab) { 29 | new Promise(resolve => { 30 | chrome.tabs.onUpdated.addListener(function _(tabId, info) { 31 | if (tabId === tab.id && info.status === 'complete') { 32 | chrome.tabs.onUpdated.removeListener(_); 33 | resolve(); 34 | } 35 | }); 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /ui/popup-load-more.js: -------------------------------------------------------------------------------- 1 | import {tabSend} from '/util/common.js'; 2 | import {$, $$} from '/util/dom.js'; 3 | import {i18n} from '/util/locale.js'; 4 | import * as popup from './popup.js'; 5 | 6 | $('#loadStop').onclick = stop; 7 | for (const el of $$('#loadMoreSection a')) 8 | el.onclick = run; 9 | 10 | inTab('query').then(num => { 11 | if (num > 0) { 12 | renderState(true); 13 | $('#loadMoreSection details').open = true; 14 | chrome.runtime.onConnect.addListener(onConnect); 15 | } 16 | }); 17 | 18 | function run(e) { 19 | e.preventDefault(); 20 | e.target.classList.add('done'); 21 | $('#loadRemain').textContent = ''; 22 | renderState(true); 23 | inTab(Number(e.target.textContent)); 24 | chrome.runtime.onConnect.addListener(onConnect); 25 | } 26 | 27 | /** 28 | * @param {Event} [event] - omit it to skip executeScript when calling explicitly 29 | */ 30 | function stop(event) { 31 | renderState(false); 32 | chrome.runtime.onConnect.removeListener(onConnect); 33 | if (event) 34 | inTab('stop'); 35 | for (const el of $$('#loadMoreSection .done')) 36 | el.classList.remove('done'); 37 | } 38 | 39 | function inTab(data) { 40 | return tabSend(popup.tab.id, ['run', {loadMore: data}]); 41 | } 42 | 43 | /** @param {chrome.runtime.Port} port */ 44 | function onConnect(port) { 45 | const {name, sender} = port; 46 | let [action, num] = String(name).split(':', 2); 47 | if (action === 'pagesRemaining' && 48 | sender && sender.tab && sender.tab.id === popup.tab.id) { 49 | port.disconnect(); 50 | num = Number(num); 51 | $('#loadRemain').textContent = num ? num + '...' : i18n('done'); 52 | if (!num) 53 | stop(); 54 | } 55 | } 56 | 57 | function renderState(running) { 58 | $('#loadMoreSection').classList.toggle('disabled', running); 59 | } 60 | -------------------------------------------------------------------------------- /ui/popup.css: -------------------------------------------------------------------------------- 1 | body { 2 | font: normal 100%/1.25 sans-serif; 3 | margin: 0; 4 | } 5 | section { 6 | padding: .5rem 1rem; 7 | } 8 | section:last-child { 9 | padding-bottom: .75rem; 10 | } 11 | section:nth-child(n + 3) { 12 | border-top: 1px solid #ccc; 13 | } 14 | section[data-status] { 15 | transition: background-color .25s; 16 | } 17 | section[data-status="true"] { 18 | background-color: darkseagreen; 19 | } 20 | section[data-status="false"] { 21 | background-color: #bbb; 22 | } 23 | section[data-status="false"] label { 24 | opacity: .5; 25 | } 26 | input { 27 | vertical-align: bottom; 28 | } 29 | label, 30 | input { 31 | cursor: pointer; 32 | } 33 | select, 34 | button { 35 | height: 1.7em; 36 | } 37 | select { 38 | background-color: #eee; 39 | border-color: #ddd; 40 | } 41 | a { 42 | text-decoration: none; 43 | } 44 | a:hover { 45 | text-decoration: underline; 46 | } 47 | [nowrap] { 48 | white-space: nowrap; 49 | } 50 | 51 | #linksSection a:not(:last-child) { 52 | margin-right: 1rem; 53 | } 54 | 55 | #genericRulesSection[disabled] #grSlot::after { 56 | content: "__MSG_genericRulesEnableHint__"; 57 | opacity: .5; 58 | } 59 | 60 | #loadMoreSection.disabled #loadStop { 61 | display: initial; 62 | } 63 | #loadMoreSection.disabled details > :not(#loadStop) { 64 | opacity: .5; 65 | pointer-events: none; 66 | user-select: none; 67 | } 68 | #loadRemain { 69 | font-size: smaller; 70 | } 71 | 72 | .failed-page .hide-when-failed { 73 | display: none !important; 74 | } 75 | .failed-page #failure { 76 | display: block; 77 | } 78 | #failure { 79 | padding: .5rem 1rem; 80 | font-size: smaller; 81 | background-color: moccasin; 82 | color: sienna; 83 | } 84 | 85 | summary { 86 | cursor: pointer; 87 | white-space: nowrap; 88 | } 89 | summary::-webkit-details-marker { 90 | width: .5rem; 91 | height: .5rem; 92 | margin: 0 .25rem; 93 | } 94 | details ul { 95 | font-size: smaller; 96 | margin: 0 0 0 1rem; 97 | padding: 0; 98 | } 99 | details li { 100 | margin: 0 0 0 .5rem; 101 | } 102 | details a { 103 | display: block; 104 | padding: 2px 0 2px 1.25rem; 105 | margin-left: -1.5rem; 106 | text-decoration: none; 107 | user-select: none; 108 | } 109 | details a:hover { 110 | text-decoration: underline; 111 | background-color: #8882; 112 | } 113 | details .done { 114 | color: darkgreen; 115 | } 116 | .full-width { 117 | padding-left: 0; 118 | } 119 | .full-width details { 120 | padding-left: 1rem; 121 | } 122 | .full-width summary { 123 | margin-left: -1rem; 124 | margin-right: -.5rem; 125 | } 126 | .full-width details ul { 127 | margin-left: 0; 128 | margin-right: -1rem; 129 | } 130 | -------------------------------------------------------------------------------- /ui/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 18 |
19 | 23 |
24 |
25 | exclude 26 | 31 |
32 |
33 |
34 |
35 | loadMore 36 |
    37 |
  • 1
  • 38 |
  • 2
  • 39 |
  • 5
  • 40 |
  • 10
  • 41 |
  • 20
  • 42 |
  • 50
  • 43 |
  • 100
  • 44 |
45 | 46 | 47 |
48 |
49 |
50 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /ui/popup.js: -------------------------------------------------------------------------------- 1 | /** @type chrome.tabs.Tab */ 2 | export let tab = {}; 3 | 4 | import {loadSettings, inBG} from '/util/common.js'; 5 | import {$} from '/util/dom.js'; 6 | import {i18n} from '/util/locale.js'; 7 | 8 | chrome.tabs.query({active: true, currentWindow: true}, tabs => { 9 | tab = tabs[0]; 10 | if (location.search) { 11 | renderFailure(); 12 | } else { 13 | import('./popup-load-more.js'); 14 | import('./popup-exclude.js'); 15 | } 16 | }); 17 | 18 | loadSettings().then(ss => { 19 | Object.assign($('#status'), { 20 | checked: ss.enabled, 21 | onchange: toggled, 22 | }); 23 | renderStatus(); 24 | }); 25 | Object.assign($('#hotkeys'), { 26 | onclick(e) { 27 | chrome.tabs.create({url: this.href}); 28 | e.preventDefault(); 29 | }, 30 | }); 31 | Object.assign($('#openOptions'), { 32 | onclick(e) { 33 | chrome.runtime.openOptionsPage(); 34 | e.preventDefault(); 35 | }, 36 | }); 37 | 38 | function renderStatus() { 39 | const enabled = $('#status').checked; 40 | $('#status').closest('[data-status]').dataset.status = enabled; 41 | $('#statusText').textContent = i18n(enabled ? 'on' : 'off'); 42 | } 43 | 44 | async function renderFailure() { 45 | const url = tab.url; 46 | const isWebUrl = url.startsWith('http'); 47 | if (isWebUrl) 48 | inBG.tryGenericRules(tab.id).then(ok => 49 | ok && import('./popup-generic-rules.js')); 50 | $('#failure').textContent = i18n( 51 | !isWebUrl ? 52 | 'failedUnsupported' : 53 | await inBG.isUrlExcluded(url) ? 54 | 'failedExcluded' : 55 | 'failedUnpageable'); 56 | } 57 | 58 | function toggled() { 59 | inBG.switchGlobalState($('#status').checked); 60 | renderStatus(); 61 | } 62 | -------------------------------------------------------------------------------- /util/common.js: -------------------------------------------------------------------------------- 1 | // inline 'export' keyword is used since everything in this module is expected to be exported 2 | 3 | import {compressToUTF16, decompressFromUTF16} from './lz-string.js'; 4 | 5 | export const RETRY_TIMEOUT = 2; 6 | export const NOP = () => {}; 7 | export const inBG = new Proxy({}, { 8 | get: (_, action) => (...data) => chrome.runtime.sendMessage({action, data}), 9 | }); 10 | 11 | const STATUS_STYLE = ` 12 | position: fixed; 13 | left: 0; 14 | bottom: 0; 15 | width: 100%; 16 | height: 24px; 17 | border: none; 18 | opacity: .7; 19 | z-index: 1000; 20 | margin: 0; 21 | padding: 0; 22 | color: white; 23 | font: bold 12px/24px sans-serif; 24 | text-align: center; 25 | transition: opacity 1s; 26 | `.replace(/\n\s+/g, '\n').trim(); 27 | 28 | /** @namespace Settings */ 29 | export const DEFAULTS = Object.freeze({ 30 | showStatus: true, 31 | darkTheme: false, 32 | enabled: true, 33 | /** seconds */ 34 | requestInterval: 2, 35 | /** minutes */ 36 | unloadAfter: 1, 37 | rules: [], 38 | genericRulesEnabled: false, 39 | genericSites: ['*'], 40 | exclusions: [], 41 | /** pixels */ 42 | pageHeightThreshold: 400, 43 | statusStyle: STATUS_STYLE + '\nbackground: black;', 44 | statusStyleError: STATUS_STYLE + '\nbackground: maroon;', 45 | }); 46 | 47 | export const getActiveTab = async () => 48 | (await chrome.tabs.query({active: true, currentWindow: true}))[0]; 49 | 50 | for (const ns of ['runtime', 'tabs']) { 51 | const obj = chrome[ns]; 52 | const fn = obj.sendMessage; 53 | obj.sendMessage = async (...args) => { 54 | const {stack} = new Error(); 55 | try { 56 | return await fn.apply(obj, args); 57 | } catch (err) { 58 | err.stack += '\nPrior to sendMessage:\n' + stack; 59 | throw err; 60 | } 61 | }; 62 | } 63 | 64 | /** 65 | * @param {string|string[]} key 66 | * @return {Promise} 67 | */ 68 | export async function loadSettings(key = Object.keys(DEFAULTS)) { 69 | const res = await chrome.storage.sync.get(key); 70 | const isKeyArray = Array.isArray(key); 71 | for (const k of isKeyArray ? key : [key]) { 72 | let v = res[k]; 73 | if (v == null) 74 | res[k] = DEFAULTS[k]; 75 | else if (v && (v = getLZ(k, v, false))) 76 | res[k] = v; 77 | } 78 | return isKeyArray ? res : res[key]; 79 | } 80 | 81 | export function getLZ(key, val, write) { 82 | if (!val) return val; 83 | let json; 84 | const d = DEFAULTS[key]; 85 | if (typeof d === 'string' || (json = Array.isArray(d))) { 86 | try { 87 | val = write ? compressToUTF16(json ? JSON.stringify(val) : val) 88 | : json ? JSON.parse(decompressFromUTF16(val)) : 89 | decompressFromUTF16(val); 90 | } catch (err) { 91 | console.warn(err, key, val); 92 | } 93 | } 94 | return val; 95 | } 96 | 97 | export function isGenericUrl(url) { 98 | return url === '^https?://.' || 99 | url === '^https?://..' || 100 | url === '^https?://.+'; 101 | } 102 | 103 | export function ignoreLastError() { 104 | chrome.runtime.lastError; // eslint-disable-line no-unused-expressions 105 | } 106 | 107 | export function arrayOrDummy(v) { 108 | return Array.isArray(v) ? v : []; 109 | } 110 | 111 | export function doDelay(seconds) { 112 | const pr = Promise.withResolvers(); 113 | setTimeout(pr.resolve, seconds * 1000); 114 | return pr.promise; 115 | } 116 | 117 | export function tabSend(tabId, msg) { 118 | return chrome.tabs.sendMessage(tabId, msg, {frameId: 0}).catch(NOP); 119 | } 120 | -------------------------------------------------------------------------------- /util/dom.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} sel 3 | * @param {Element|Document} base 4 | * @return {?Element} 5 | */ 6 | export function $(sel, base = document) { 7 | return sel.startsWith('#') && !sel.includes(' ') && /^#[\w\\]+$/.test(sel) ? 8 | base.getElementById(sel.slice(1)) : 9 | base.querySelector(sel); 10 | } 11 | 12 | /** 13 | * @param {string} sel 14 | * @param {Element|Document} base 15 | * @return {NodeList} 16 | */ 17 | export function $$(sel, base = document) { 18 | return base.querySelectorAll(sel); 19 | } 20 | 21 | export function toggleDarkTheme(force = 'darkTheme' in localStorage) { 22 | for (const el of $$('link[media]')) 23 | el.media = force ? 'screen' : '(prefers-color-scheme: dark)'; 24 | } 25 | 26 | toggleDarkTheme(); 27 | chrome.storage.sync.onChanged.addListener(ch => { 28 | if ((ch = ch.darkTheme)) 29 | toggleDarkTheme(ch.newValue); 30 | }); 31 | -------------------------------------------------------------------------------- /util/locale.js: -------------------------------------------------------------------------------- 1 | export { 2 | i18n, 3 | }; 4 | 5 | const TAG = /(<\S.*?>)/; 6 | 7 | onMutation([{addedNodes: document.querySelectorAll('[tl]')}]); 8 | 9 | if (document.readyState === 'loading') { 10 | const mo = new MutationObserver(onMutation); 11 | mo.observe(document, {subtree: true, childList: true}); 12 | document.addEventListener('DOMContentLoaded', () => mo.disconnect(), {once: true}); 13 | } 14 | 15 | // 'observer' is present when invoked by real mutations 16 | // so when absent we translate all supplied elements with no further checks 17 | function onMutation(mutations, observer) { 18 | for (const m of mutations) { 19 | for (const node of m.addedNodes) { 20 | if (!observer || node.tagName && node.hasAttribute('tl')) { 21 | const str = i18n(node.textContent.trim()); 22 | if (TAG.test(str)) 23 | renderTags(node, str); 24 | else 25 | node.firstChild.nodeValue = str; 26 | } 27 | } 28 | } 29 | } 30 | 31 | function i18n(...args) { 32 | return chrome.i18n.getMessage(...args); 33 | } 34 | 35 | function renderTags(el, str) { 36 | el.textContent = ''; 37 | el.append(...str.split(TAG).map(renderTagOrString)); 38 | } 39 | 40 | function renderTagOrString(str) { 41 | if (str.startsWith('<') && str.endsWith('>')) { 42 | const el = document.createElement('b'); 43 | el.textContent = str.slice(1, -1); 44 | return el; 45 | } else 46 | return str; 47 | } 48 | -------------------------------------------------------------------------------- /util/lz-string.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // private property 4 | var 5 | {fromCharCode} = String, 6 | streamData, 7 | streamDataVal, 8 | streamDataPosition, 9 | streamBitsPerChar; 10 | 11 | function streamBits(value, numBitsMask) { 12 | for (var i = 0; numBitsMask >>= 1; i++) { 13 | // shifting has precedence over bitmasking 14 | streamDataVal = value >> i & 1 | streamDataVal << 1; 15 | if (++streamDataPosition === streamBitsPerChar) { 16 | streamDataPosition = 0; 17 | streamData.push(streamDataVal + 32); 18 | streamDataVal = 0; 19 | } 20 | } 21 | } 22 | 23 | export function compressToUTF16(uncompressed) { 24 | if (uncompressed == null) 25 | return ''; 26 | var res = []; 27 | // data - empty stream 28 | streamData = []; 29 | // davaVal 30 | streamDataVal = 0; 31 | // dataPosition 32 | streamDataPosition = 0; 33 | streamBitsPerChar = 15; 34 | var j = 0, k = 0, value = 0, 35 | node = [3], // first node will always be initialised like this. 36 | // we should never output the root anyway, 37 | // so we initiate with terminating token 38 | // Also, dictionary[1] will be overwritten 39 | // by the first charCode 40 | dictionary = [2, 2, node], 41 | freshNode = true, 42 | c = 0, 43 | dictSize = 3, 44 | numBitsMask = 0b100; 45 | 46 | if (uncompressed.length) { 47 | // If there is a string, the first charCode is guaranteed to 48 | // be new, so we write it to output stream, and add it to the 49 | // dictionary. For the same reason we can initialize freshNode 50 | // as true, and new_node, node and dictSize as if 51 | // it was already added to the dictionary (see above). 52 | 53 | c = uncompressed.charCodeAt(0); 54 | 55 | // == Write first charCode token to output == 56 | 57 | // 8 or 16 bit? 58 | value = c < 256 ? 0 : 1; 59 | 60 | // insert "new 8/16 bit charCode" token 61 | // into bitstream (value 1) 62 | streamBits(value, numBitsMask); 63 | streamBits(c, value ? 0b10000000000000000 : 0b100000000); 64 | 65 | // Add charCode to the dictionary. 66 | dictionary[1] = c; 67 | 68 | nextchar: 69 | for (j = 1; j < uncompressed.length; j++) { 70 | if (streamData.length > 8000) { 71 | res.push(fromCharCode(...streamData)); 72 | streamData.length = 0; 73 | } 74 | c = uncompressed.charCodeAt(j); 75 | // does the new charCode match an existing prefix? 76 | for (k = 1; k < node.length; k += 2) { 77 | if (node[k] === c) { 78 | node = node[k + 1]; 79 | continue nextchar; 80 | } 81 | } 82 | // we only end up here if there is no matching char 83 | 84 | // Prefix+charCode does not exist in trie yet. 85 | // We write the prefix to the bitstream, and add 86 | // the new charCode to the dictionary if it's new 87 | // Then we set `node` to the root node matching 88 | // the charCode. 89 | 90 | if (freshNode) { 91 | // Prefix is a freshly added character token, 92 | // which was already written to the bitstream 93 | freshNode = false; 94 | } else { 95 | // write out the current prefix token 96 | streamBits(node[0], numBitsMask); 97 | } 98 | 99 | // Is the new charCode a new character 100 | // that needs to be stored at the root? 101 | k = 1; 102 | while (dictionary[k] !== c && k < dictionary.length) { 103 | k += 2; 104 | } 105 | if (k === dictionary.length) { 106 | // increase token bitlength if necessary 107 | if (++dictSize >= numBitsMask) { 108 | numBitsMask <<= 1; 109 | } 110 | 111 | // insert "new 8/16 bit charCode" token, 112 | // see comments above for explanation 113 | value = c < 256 ? 0 : 1; 114 | streamBits(value, numBitsMask); 115 | streamBits(c, value ? 0b10000000000000000 : 0b100000000); 116 | 117 | dictionary.push(c); 118 | dictionary.push([dictSize]); 119 | // Note of that we already wrote 120 | // the charCode token to the bitstream 121 | freshNode = true; 122 | } 123 | // add node representing prefix + new charCode to trie 124 | node.push(c); 125 | node.push([++dictSize]); 126 | // increase token bitlength if necessary 127 | if (dictSize >= numBitsMask) { 128 | numBitsMask <<= 1; 129 | } 130 | // set node to first charCode of new prefix 131 | // k is guaranteed to be at the current charCode, 132 | // since we either broke out of the while loop 133 | // when it matched, or just added the new charCode 134 | node = dictionary[k + 1]; 135 | 136 | } 137 | 138 | // === Write last prefix to output === 139 | if (freshNode) { 140 | // character token already written to output 141 | freshNode = false; 142 | } else { 143 | // write out the prefix token 144 | streamBits(node[0], numBitsMask); 145 | 146 | } 147 | 148 | // Is c a new character? 149 | k = 1; 150 | while (dictionary[k] !== c && k < dictionary.length) { 151 | k += 2; 152 | } 153 | if (k === dictionary.length) { 154 | // increase token bitlength if necessary 155 | if (++dictSize >= numBitsMask) { 156 | numBitsMask <<= 1; 157 | } 158 | // insert "new 8/16 bit charCode" token, 159 | // see comments above for explanation 160 | value = c < 256 ? 0 : 1; 161 | streamBits(value, numBitsMask); 162 | streamBits(c, value ? 0b10000000000000000 : 0b100000000); 163 | } 164 | // increase token bitlength if necessary 165 | if (++dictSize >= numBitsMask) { 166 | numBitsMask <<= 1; 167 | } 168 | } 169 | 170 | // Mark the end of the stream 171 | streamBits(2, numBitsMask); 172 | 173 | 174 | // Flush the last char 175 | streamDataVal <<= streamBitsPerChar - streamDataPosition; 176 | streamData.push(streamDataVal + 32); 177 | res.push(fromCharCode(...streamData), ' '); 178 | streamData.length = 0; 179 | return res.join(''); 180 | } 181 | 182 | export function decompressFromUTF16(compressed) { 183 | if (compressed == null) return ''; 184 | if (compressed === '') return null; 185 | var {length} = compressed, 186 | resetBits = 15, 187 | dictionary = [0, 1, 2], 188 | enlargeIn = 4, 189 | dictSize = 4, 190 | numBits = 3, 191 | entry = "", 192 | result = [], 193 | w = "", 194 | bits = 0, 195 | maxpower = 2, 196 | power = 0, 197 | c = "", 198 | data_val = compressed.charCodeAt(0) - 32, 199 | data_position = resetBits, 200 | data_index = 1; 201 | 202 | // Get first token, guaranteed to be either 203 | // a new character token (8 or 16 bits) 204 | // or end of stream token. 205 | while (power !== maxpower) { 206 | // shifting has precedence over bitmasking 207 | bits += (data_val >> --data_position & 1) << power++; 208 | if (data_position === 0) { 209 | data_position = resetBits; 210 | data_val = compressed.charCodeAt(data_index++) - 32; 211 | } 212 | } 213 | 214 | // if end of stream token, return empty string 215 | if (bits === 2) { 216 | return ""; 217 | } 218 | 219 | // else, get character 220 | maxpower = bits * 8 + 8; 221 | bits = power = 0; 222 | while (power !== maxpower) { 223 | // shifting has precedence over bitmasking 224 | bits += (data_val >> --data_position & 1) << power++; 225 | if (data_position === 0) { 226 | data_position = resetBits; 227 | data_val = compressed.charCodeAt(data_index++) - 32; 228 | } 229 | } 230 | c = fromCharCode(bits); 231 | dictionary[3] = c; 232 | w = c; 233 | result.push(c); 234 | 235 | // read rest of string 236 | while (data_index <= length) { 237 | // read out next token 238 | maxpower = numBits; 239 | bits = power = 0; 240 | while (power !== maxpower) { 241 | // shifting has precedence over bitmasking 242 | bits += (data_val >> --data_position & 1) << power++; 243 | if (data_position === 0) { 244 | data_position = resetBits; 245 | data_val = compressed.charCodeAt(data_index++) - 32; 246 | } 247 | } 248 | 249 | // 0 or 1 implies new character token 250 | if (bits < 2) { 251 | maxpower = (8 + 8 * bits); 252 | bits = power = 0; 253 | while (power !== maxpower) { 254 | // shifting has precedence over bitmasking 255 | bits += (data_val >> --data_position & 1) << power++; 256 | if (data_position === 0) { 257 | data_position = resetBits; 258 | data_val = compressed.charCodeAt(data_index++) - 32; 259 | } 260 | } 261 | dictionary[dictSize] = fromCharCode(bits); 262 | bits = dictSize++; 263 | if (--enlargeIn === 0) { 264 | enlargeIn = 1 << numBits++; 265 | } 266 | } else if (bits === 2) { 267 | // end of stream token 268 | return result.join(''); 269 | } 270 | 271 | if (bits > dictionary.length) { 272 | return null; 273 | } 274 | entry = bits < dictionary.length ? dictionary[bits] : w + w.charAt(0); 275 | result.push(entry); 276 | // Add w+entry[0] to the dictionary. 277 | dictionary[dictSize++] = w + entry.charAt(0); 278 | 279 | w = entry; 280 | 281 | if (--enlargeIn === 0) { 282 | enlargeIn = 1 << numBits++; 283 | } 284 | 285 | } 286 | return ""; 287 | } 288 | -------------------------------------------------------------------------------- /util/storage-idb.js: -------------------------------------------------------------------------------- 1 | /** @type IDBDatabase */ 2 | let db = null; 3 | const mutex = []; 4 | const DB_NAME = 'db'; 5 | const DEFAULT_STORE_NAME = 'cache'; 6 | const EXEC_HANDLER = { 7 | get({cfg = {}}, method) { 8 | const {resolve: ok, reject: err, promise: p} = Promise.withResolvers(); 9 | return method === 'READ' || method === 'WRITE' 10 | ? (doExec(cfg, method, null, ok, err), p) 11 | : (...args) => (doExec(cfg, method, args, ok, err), p); 12 | }, 13 | }; 14 | /** @typedef {IDBObjectStore | IDBIndex} IDBTarget */ 15 | /** @typedef {IDBTarget | {READ: IDBTarget} | {WRITE: IDBTarget}} IDB */ 16 | /** @type {IDB | ((cfg: ExecConfig) => IDB) } */ 17 | export const dbExec = new Proxy(cfg => new Proxy({cfg}, EXEC_HANDLER), EXEC_HANDLER); 18 | 19 | /** 20 | * @typedef ExecConfig 21 | * @prop {String} [store=cache] 22 | * @prop {Boolean} [write] 23 | * @prop {String} [index] 24 | */ 25 | 26 | function doExec(/** ExecConfig */cfg, k, args, resolve, reject) { 27 | if (!db) { 28 | doOpen(cfg, k, args, resolve, reject); 29 | return; 30 | } 31 | const write = k === 'WRITE' || k === 'put' || k === 'clear' || k === 'delete'; 32 | const storeName = cfg.store || DEFAULT_STORE_NAME; 33 | let op = db 34 | .transaction(storeName, write ? 'readwrite' : 'readonly') 35 | .objectStore(storeName); 36 | if (cfg.index) 37 | op = op.index(cfg.index); 38 | if (k !== 'READ' && k !== 'WRITE') { 39 | op = op[k](...args); 40 | op.__resolve = resolve; 41 | op.onsuccess = resolveResult; 42 | op.onerror = reject; 43 | } else { 44 | resolve(op); 45 | } 46 | } 47 | 48 | function doOpen(...args) { 49 | mutex.push(args); 50 | if (mutex.length > 1) 51 | return; 52 | const op = indexedDB.open(DB_NAME, 2); 53 | op.onsuccess = onDbOpened; 54 | op.onupgradeneeded = onDbUpgraded; 55 | } 56 | 57 | function onDbOpened(e) { 58 | db = e.target.result; 59 | while (mutex.length) 60 | doExec(...mutex.shift()); 61 | } 62 | 63 | function onDbUpgraded(e) { 64 | db = e.target.result; 65 | if (!db.objectStoreNames.contains(DEFAULT_STORE_NAME)) 66 | db.createObjectStore(DEFAULT_STORE_NAME, {keyPath: 'url'}) 67 | .createIndex('id', 'id', {unique: true}); 68 | for (const name of ['urlCache', 'data']) 69 | if (!db.objectStoreNames.contains(name)) 70 | db.createObjectStore(name); 71 | } 72 | 73 | function resolveResult({target: op}) { 74 | return op.__resolve(op.result); 75 | } 76 | --------------------------------------------------------------------------------