Compare commits

...

162 Commits

Author SHA1 Message Date
Derrick Hammer 22ca594402 *Whitelist api-metadata.json 2022-03-26 19:39:50 -04:00
Derrick Hammer 5ab05945cd Revert "*Move api data"
This reverts commit b39d81d20c.
2022-03-26 18:45:20 -04:00
Derrick Hammer b39d81d20c *Move api data 2022-03-26 18:23:24 -04:00
Derrick Hammer 71c9dc2108 *Empty prepublish command 2022-03-26 18:02:40 -04:00
Derrick Hammer ad64be439a *Remove test 2022-03-26 17:59:57 -04:00
Derrick Hammer 14e23759c6 *Fix apiMetadata 2022-03-23 21:14:21 -04:00
Derrick Hammer 9ee7c32ed0 *Merge in @types package 2022-03-23 21:03:59 -04:00
Derrick Hammer 1f7f73c23b *Remove chrome.runtime check and namespace the package 2022-03-23 20:58:46 -04:00
renovate[bot] f818ecbac3
chore(deps): update dependency shelljs to v0.8.5 [security] (#358)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-18 21:38:47 +01:00
Luca Greco becce92d47
chore: Run update apt before installing xserver-xephyr in the CI job (#359) 2022-01-18 21:33:09 +01:00
Federico Brigante 780518ed1d
fix: enable webextension-polyfill usage via webpack ProvidePlugin (#351)
* Enable usage via `ProvidePlugin`
* Use `globalThis`
* Update lint to forbid `browser` global usage
2022-01-18 21:12:53 +01:00
Federico Brigante 31ed31a6e0
chore: Update eslint to enforce quotes and fix the existing linting errors (#355) 2022-01-18 21:10:34 +01:00
Renovate Bot 2d75968a98 chore(deps): update dependency chromedriver to v96 2021-11-26 21:26:14 +01:00
Luca Greco 92799f2f0a chore: Bump nodejs version used by CircleCI jobs to nodejs v12 2021-11-26 21:08:30 +01:00
Luca Greco 5dbb8d94b5
chore: Fix missing codecov reports (#345) 2021-11-03 15:33:19 +01:00
William Durand 7236f4a985
Use new codecov uploader via Circle ORB (#341) 2021-10-27 19:23:31 +02:00
Lusito 685446dde2
docs: Updated readme for @types/webextension-polyfill (#330) 2021-08-23 14:23:53 +02:00
renovate[bot] 4b2afe89fd
chore(deps): update babel monorepo (#305)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:42:07 +02:00
renovate[bot] 3092c97fae
chore(deps): update dependency mocha to v8.4.0 (#314)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:41:39 +02:00
renovate[bot] bbf2ab7d51
chore(deps): update dependency codecov to v3.8.2 (#310)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:41:19 +02:00
renovate[bot] fd614803ae
chore(deps): update dependency eslint to v7.25.0 (#308)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:41:05 +02:00
renovate[bot] 3df12f47c5
chore(deps): update dependency grunt-replace to v2.0.2 (#309)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:40:46 +02:00
renovate[bot] 439ed24f21
chore(deps): update dependency grunt to v1.4.0 (#306)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:40:16 +02:00
renovate[bot] d4c9f9a295
chore(deps): update dependency chromedriver to v90 (#304)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-05-07 15:18:22 +02:00
Luca Greco 50be150c25 chore: bump version for release 0.8.0 2021-04-20 13:12:38 +02:00
renovate[bot] e48cc39170
chore(deps): update babel monorepo (#291)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:27:41 +02:00
renovate[bot] fecd59bd72
chore(deps): update dependency geckodriver to v1.22.3 (#300)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:27:04 +02:00
renovate[bot] b48389cdad
chore(deps): update dependency sinon to v10 (#298)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:26:27 +02:00
renovate[bot] c41212d9d7
chore(deps): update dependency eslint to v7.24.0 (#296)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:26:09 +02:00
renovate[bot] 454ef23bd7
chore(deps): update dependency mocha to v8.3.2 (#295)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:25:45 +02:00
renovate[bot] 919987972a
chore(deps): update dependency chai to v4.3.4 (#286)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-04-13 16:24:43 +02:00
Luca Greco 5ab825b83f
fix: Reject with real Error instances like Firefox does (#293)
Co-authored-by: Federico Brigante <me@fregante.com>
2021-03-18 18:07:16 +01:00
renovate[bot] fa4b26f406
chore(deps): update dependency mocha to v8.3.1 (#290)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-09 21:42:49 +01:00
renovate[bot] 6b619bc709
chore(deps): update dependency tape to v5.2.2 (#287)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-09 21:42:35 +01:00
renovate[bot] 42a476661c
chore(deps): update dependency geckodriver to v1.22.2 (#289)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-09 21:42:03 +01:00
renovate[bot] 52231dea6d
chore(deps): update dependency chromedriver to v89 (#288)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-09 21:41:44 +01:00
renovate[bot] df8f06d9e1
chore(deps): update dependency chai to v4.3.1 (#285)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-03 16:25:27 +01:00
renovate[bot] a03a7950f0
chore(deps): update dependency tape to v5.2.1 (#284)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-03 16:25:08 +01:00
renovate[bot] 6a073cec9e
chore(deps): update dependency eslint to v7.21.0 (#283)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-03 16:24:24 +01:00
renovate[bot] 3f48baf550
chore(deps): update dependency grunt-replace to v2 (#282)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-03 16:23:54 +01:00
renovate[bot] ed32155c32
chore(deps): update babel monorepo (#281)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-03-03 16:22:59 +01:00
renovate[bot] 29a674a8eb
chore(deps): update dependency tape to v5.2.0 (#280)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-22 14:12:07 +01:00
renovate[bot] f59e78abb7
chore(deps): update babel monorepo to v7.12.17 (#279)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-22 14:11:10 +01:00
Luca Greco 62f6848bee
chore: Removed unused async-wait-until dev dependency (#278) 2021-02-16 15:54:20 +01:00
renovate[bot] c47e4e8330
chore(deps): update dependency eslint to v7.20.0 (#275)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-15 15:12:16 +01:00
renovate[bot] 413622f275
chore(deps): update babel monorepo to v7.12.16 (#274)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-12 12:59:21 +01:00
renovate[bot] 4758095e29
chore(deps): update dependency mocha to v8.3.0 (#273)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-12 12:58:57 +01:00
renovate[bot] 19a753c01c
chore(deps): update dependency tape to v5 (#272)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-05 11:46:43 +01:00
renovate[bot] f4c7c831db
chore(deps): update dependency nyc to v15 (#270)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-05 11:45:50 +01:00
renovate[bot] c7a431ad39
chore(deps): update dependency sinon to v9 (#271)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-05 11:41:44 +01:00
renovate[bot] 390d7c8d51
chore(deps): update dependency mocha to v8 (#269)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 21:06:46 +01:00
renovate[bot] 8caec99e2e
chore(deps): update dependency istanbul-lib-instrument to v4 (#267)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 21:05:45 +01:00
renovate[bot] 0ae61e6b45
chore(deps): update dependency chai to v4.3.0 (#266)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 21:04:37 +01:00
renovate[bot] f80bed949f
chore(deps): update dependency eslint to v7 (#265)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 21:04:16 +01:00
renovate[bot] d0b0a5c999
chore(deps): update dependency cross-env to v7 (#264)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 20:59:46 +01:00
renovate[bot] 8f33cd0b01
chore(deps): update dependency chromedriver to v88 (#263)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 20:58:42 +01:00
renovate[bot] 78bc8e1bbd
chore(deps): update dependency browserify to v17 (#262)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-04 20:56:39 +01:00
renovate[bot] a79e31dc40
chore(deps): update dependency tmp to v0.2.1 (#261)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-03 20:07:33 +01:00
renovate[bot] 85ec16a437
chore(deps): pin dependencies (#260)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-03 18:57:40 +01:00
renovate[bot] 24bab250d2
chore: Add renovate.json (#259)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2021-02-03 18:33:31 +01:00
Luca Greco 614a1f3f36
chore(ci): Migrate CI jobs to circleci (#256) 2021-01-21 13:20:11 +01:00
Doug Parker 716c90bca4 fix: wrap `onRequestFinished` to use promises
Fixes #249.

This updates `browser.devtools.network.onRequestFinished` to emit an
object with a promisified `getContent()` property. This brings the
polyfill implementation in line with Firefox's implementation, although
MDN documentation is still inaccurate at the moment.

Also updates some out of date documentation with `makeCallback()` and
`wrapAsyncFunction()`.
2020-12-10 23:08:57 +01:00
Rob Wu 3ba72c96a9 fix(test): fix expectation of tabs-sendmessage in Firefox (#251)
Upstream regression got fixed @ https://bugzilla.mozilla.org/show_bug.cgi?id=1665568
2020-12-10 15:35:29 +01:00
Rob Wu 85c5dfb84a chore(deps): Updated chromedriver to version 87.0.2 2020-12-08 15:34:43 +01:00
Luca Greco 93203c6995 chore: bump version for release 0.7.0 2020-11-10 21:14:55 +01:00
Akhil Panchal a0cd3fde15
feat: Added devtools.panels.elements.createSidebarPane to metadata (#247) 2020-10-29 15:19:10 +01:00
infokiller 55503f4c93
feat: Add chrome.goBack and chrome.goForward (#244)
Fixes #243

APIs added in Chrome 72:
- https://developer.chrome.com/extensions/tabs#method-goBack
- https://developer.chrome.com/extensions/tabs#method-goForward
2020-10-29 15:18:33 +01:00
Rob Wu 8c7be46873 fix: replace --output option of webpack
Currently the build/test fails with the following output:

```
Test webextension-polyfill bundled with webpack
===============================================
[webpack-cli] Unknown argument: --output
[webpack-cli] Unknown argument: /tmp/webpack-bundle.js
? Which flags do you want to use? …
✔ --entry: The entry point(s) of your application e.g. ./src/main.js
✔ --config: Provide path to a webpack configuration file e.g. ./webpack.config.js
✔ --color: Enable/Disable colors on console
✔ --merge: Merge two or more configurations using webpack-merge e.g. -c ./webpack.config.js -c ./webpack.test.config.js --merge
✔ --progress: Print compilation progress during build
✔ --help: Outputs list of supported flags
✔ --output-path: Output location of the file generated by webpack e.g. ./dist/
```

Regressed by:
https://github.com/webpack/webpack-cli/pull/1855
2f36b9d858

`--output` has been renamed to `--output-path` (`-o` in both cases), but
stopped supporting file names.  To output to a specific absolute path,
`--output-path` and `--output-filename` must both be specified, with the
directory in the former and the filename in the latter.
2020-10-15 15:19:16 +02:00
Timofey Kuznetsov 01fb67f047
docs(README): Updated code in "Usage with webpack without bundling" section (#240) 2020-10-05 12:19:29 +02:00
Lusito b0596ad616 docs: Add TypeScript Usage Hints 2020-09-17 14:24:45 +02:00
Rob Wu d6a789bf54 fix(test): fix expectation of tabs-sendmessage-expectation in Firefox
Work-around for upstream regression @ https://bugzilla.mozilla.org/show_bug.cgi?id=1665568
2020-09-17 13:19:55 +02:00
Rob Wu 5f13763d5e chore(deps): Updated chromedriver to version 85.0.1 2020-09-17 13:19:55 +02:00
Rob Wu 3f4f0b9ef5 fix(travis): Run tests with Node 10 instead of 8 (#238)
CI is currently failing because package.json refers chromedriver
^80.0.1, which also matches 80.0.2.

In 80.0.2, chromedriver updated the `extract-zip` dependency:
16151de4c7

extract-zip 2.0.0 has dropped support for Node <10, e.g. by using APIs
that were introduced in Node 10:
https://github.com/maxogden/extract-zip/blob/v2.0.0/index.js#L11

which triggers the following error when run on earlier versions of Node:

```
> chromedriver@80.0.2 install /home/travis/build/mozilla/webextension-polyfill/node_modules/chromedriver
> node install.js

internal/util.js:214
    throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'function');
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type function
    at promisify (internal/util.js:214:11)
    at Object.<anonymous> (/home/travis/build/mozilla/webextension-polyfill/node_modules/extract-zip/index.js:11:18)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/home/travis/build/mozilla/webextension-polyfill/node_modules/chromedriver/install.js:14:20)
```

This commit fixes the issue by running tests with Node 10.
Node 8 had become end-of-life on 2019-12-31 anyway.
2020-09-17 13:19:35 +02:00
Luca Greco faa22a4df1
doc: Updated README.md notes related to MSEdge (#222) 2020-03-03 15:12:39 +01:00
Rob Wu 2a4c9a8c79
chore: Remove IRC notification from Travis (#220)
We moved from IRC to Matrix.

... but the project is stable with little new development so we can as
well remove the notifications.
2020-02-19 23:49:46 +01:00
Rob Wu b22e05870d
chore(deps): Updated chromedriver to version 80.0.1 (#221) 2020-02-19 23:48:46 +01:00
Luca Greco c77e9fb89d chore: bump version for release 0.6.0 2019-12-23 13:26:35 +01:00
Luca Greco 5c8a743cb2
doc: Add section related to basic setup with ES6 module loader (#216) 2019-12-23 13:09:26 +01:00
Luca Greco f85b5d8e5b
fix: Update babel deps to babel 7 (#214)
* fix: Update babel deps to babel 7
* chore: Replaced @babel/transfor-umd-modules with a small custom babel transformer script
* test: Added minimal integration test as smoke test for importing polyfill as es6 module
2019-12-12 19:00:46 +01:00
Luca Greco 2005a2ca22 chore: Updated sinon to version 7.5.0 2019-11-27 13:38:52 +01:00
Luca Greco 5f1fbcc72c chore: Updated grunt-coveralls to version 2.0.0 2019-11-27 13:38:52 +01:00
Luca Greco 94a4f73371 chore: Updated gruntify-eslint to version 5.0.0 2019-11-27 13:38:52 +01:00
Luca Greco 99dc57cda0 chore: Updated mocha to version 4.2.0 2019-11-27 13:38:52 +01:00
Luca Greco d44187c2e9 chore: Updated chai to version 4.2.0 2019-11-27 13:38:52 +01:00
Luca Greco 57af39d0c5 chore: Updated babel-eslint to version 10.0.3 2019-11-27 13:38:52 +01:00
Luca Greco ff38ac3b6c chore: Updated cross-env to version 6.0.3 2019-11-27 13:38:52 +01:00
Luca Greco ce73bce4a2 chore: Updated nyc to version 14.1.1 2019-11-27 13:38:52 +01:00
Luca Greco 75b569b250 chore: Updated instanbul-lib-instrument to version 3.3.0 2019-11-27 13:38:52 +01:00
Luca Greco 8dd76b0e37 chore: Updated tmp to version 0.1.0 2019-11-27 13:38:52 +01:00
Manvel Saroyan 87bdfa844d fix: Added missing chrome privacy api settings (#205) 2019-11-21 15:21:06 +01:00
dependabot[bot] b8e374a37a chore(deps-dev): bump eslint from 3.19.0 to 6.6.0 (#209)
Bumps [eslint](https://github.com/eslint/eslint) from 3.19.0 to 6.6.0.
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/master/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v3.19.0...v6.6.0)

Signed-off-by: dependabot[bot] <support@github.com>
2019-11-21 14:24:41 +01:00
Manvel Saroyan 5f7a8458c9 chore(deps): Updated chromedriver to version 78.0.1 2019-10-29 23:42:45 +00:00
Luca Greco be611156bc chore: bump version for release 0.5.0 2019-09-27 00:04:25 +02:00
Luca Greco 06ebcbd07f
fix(travis): Added xvfb service to travis config (#203) 2019-09-24 21:20:42 +02:00
ExE Boss 04a9e3a223 chore: Add `.editorconfig` (#188) 2019-09-08 15:38:25 +02:00
Shubham Chinda 3929b9f760 fix: Remove runtime.getBrowserInfo() (#200) 2019-08-01 19:01:38 +02:00
Federico Brigante 44a473db5d docs(README): Add suggested webpack usage (#194) 2019-08-01 18:53:23 +02:00
Luca Greco 6b8e7e18ed
chore(deps): Updated chromedriver to version 76.0.0 (#199) 2019-08-01 17:16:24 +02:00
Siddharth M 51998c1c64 chore: Fixed typos in README.md file (#197) 2019-08-01 13:30:57 +02:00
Rob Wu ad207a84b9
fix: Throw error when loaded in non-extension contexts (#190)
Fixes #186
2019-07-18 15:21:49 +02:00
Mozilla-GitHub-Standards 10bc37b342 chore: Add Mozilla Code of Conduct file
Fixes #181.

_(Message COC002)_
2019-04-16 11:39:12 +02:00
Rob Wu 6fb04ebc66 docs(README): Clarify why Chrome-only methods have no Promise (#183) 2019-04-09 18:27:08 +02:00
ExE Boss 3aad2418d8 test(devtools): Fix intermittent DevTools API test timeout (#177) 2019-03-20 12:27:09 +01:00
Luca Greco 949f08cc7d chore: bump version for release 0.4.0 2019-02-06 12:40:54 +01:00
Luca Greco 6f178c56da
fix: browser.devtools.inspectedWindow.eval promise should always resolve to an array (#175)
* fix: browser.devtools.inspectedWindow.eval promise should always resolve to an array
* test(integration): Add test for browser.devtools.inspectedWindow.eval API
2019-02-01 08:38:35 +01:00
Luca Greco e6601af79c
doc: Update MSEdge note in README.md (#176) 2019-01-31 16:58:43 +01:00
Luca Greco cdbb3115e8 chore: Small tweaks to the eslint config files (follow-up for #167) 2019-01-28 18:56:40 +01:00
ExE Boss 83ec9e70ad test(integration): Use node for running test scripts (#167)
* test(integration): Use node for running browser smoketests
* test(integration): Use node for running test scripts
2019-01-28 18:49:25 +01:00
serv-inc 34a6ab4559 docs(README): Add reminder to include browser-polyfill.js before other bg scripts (#160) 2018-11-08 15:09:14 +01:00
ExE Boss 7b46d25db2 refactor: Make the `wrapAPIs` function take the `chrome` object as a parameter (#139) 2018-08-27 15:50:40 +02:00
Luca Greco cf135db59e chore: bump version for release 0.3.1 2018-08-21 12:03:52 +02:00
Luca Greco ebd28186a1
fix: Prevent a webpage document element to be detected as the Extension API object (#153) 2018-08-15 22:33:37 +02:00
Mike Frysinger 450eee59a3 doc: fix broken link in README 2018-08-02 09:20:22 +02:00
ExE Boss 26683389ea
chore: Replace post-processed warning message with single-line string literal (#152) 2018-07-27 17:37:29 +02:00
Luca Greco 5e4796c116 chore: bump version for release 0.3.0 2018-07-19 16:48:08 +02:00
Luca Greco e17f1e1763 chore: Fixed npm badge in README.md 2018-07-19 16:43:57 +02:00
Luca Greco 440857e5f8
doc: Rewrite README.md and move build and contribution details into a separate doc file (#147) 2018-07-19 15:56:49 +02:00
Stuart Colville 890a99ae62 chore: Updated npm token in the travis config file (#149) 2018-07-16 13:59:40 +02:00
Rob Wu d77a418537 feat: Support promises in privacy namespace 2018-07-11 18:04:32 +02:00
PoziWorld ea82fbf556 chore: Fixed typos in inline comments (#144) 2018-07-07 17:44:19 +02:00
PoziWorld 33c2afb578 chore: Fixed typo in the README file (#143) 2018-07-07 17:43:17 +02:00
ExE Boss 4712d9274d chore: Fixed build and integration tests when installed using pnpm (#127) 2018-07-04 13:47:41 +02:00
Rob Wu d612352bba fix: resolve to undefined instead of an empty array 2018-07-04 13:17:09 +02:00
Simon Lydell 4e1e98add2 fix: sendMessage promise should resolve to undefined when no listeners reply 2018-07-04 13:06:42 +02:00
Rob Wu 7ff6e8a1dc chore: Stop swallowing errors in .sh tests
The Bash shell scripts ignored errors in all but the last line.
This commit adds `set -eo pipefail` to fix the issue:

`set -e` causes the script to exit as soon as any command exits with a
non-zero exit code. When pipes are used, this flag only applies to the
last command in a pipe. The `set -o pipefail` option ensures that the
script is also exited with a non-zero exit code when any command in the
pipe fails.
2018-06-20 15:29:03 +02:00
ExE Boss c0bf94f2eb chore: Fix the `\n` character preceding `echo` output in shell scripts (#136) 2018-06-20 00:33:12 +02:00
ExE Boss 80f4caf453 chore: Use `delete window.browser` in `setupTestDOMWindow` (#128)
This patch remove a workaround introduced in #2, because it has been fixed upstream and the workaround is not needed anymore (when using a nodejs version >= 8).
2018-06-19 23:36:50 +02:00
ExE Boss 3a6d76a88f chore: Cleaned up travis config (#129)
* Removed duplicate `sudo` entry in `.travis.yml`
* Rephrased log message while running cross-browsers integration tests.
2018-06-19 23:29:35 +02:00
Rob Wu 2537b23837 fix: add tabs.discard 2018-06-15 10:49:53 -07:00
Rob Wu 32863899bd style: alphabetically sort methods in tabs namespace 2018-06-15 10:49:53 -07:00
Rob Wu a3cb260c8e fix: Remove non-existing pageAction.getIcon
- Alphabetically sort keys
- Remove non-existing pageAction.getIcon
  (neither Firefox nor Chrome support this method).
2018-06-15 10:49:53 -07:00
Rob Wu e2754582c7 fix: Add missing management.setEnabled
setEnabled is partially implemented in Firefox:
- https://bugzil.la/1282982
- https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/management/setEnabled

The management API has many more methods in Chrome,
Firefox does not support them:
- createAppShortcut
- generateAppForLink
- getPermissionWarningsById
- getPermissionWarningsByManifest
- launchApp
- setLaunchType
- uninstall
2018-06-15 10:49:53 -07:00
Rob Wu 28377724ca style: alphabetically sort history keys 2018-06-15 10:49:53 -07:00
Rob Wu 597788817e fix: Fix downloads schemas
- Alphabetically sort keys
- Add `"fallbackToNoCallback": true` to `open` and `show`
  because these methods do currently not take any callbacks in Chrome:
  https://developer.chrome.com/extensions/downloads#method-open
  https://developer.chrome.com/extensions/downloads#method-show
- Chrome has a `downloads.acceptDanger` method, but Firefox does not,
  so this is not included in the schema.
2018-06-15 10:49:53 -07:00
Rob Wu fc25bd3e4c style: Alphabetically sort keys in contextMenus 2018-06-15 10:49:53 -07:00
Rob Wu 1981c59d94 fix: Add missing browserAction APIs (#99)
Note that the "openPopup" method is only available to the dev channel:
c2b078825a/chrome/common/extensions/api/_api_features.json (178)
https://crbug.com/436489
2018-06-15 10:49:53 -07:00
Rob Wu 5046a3f400 fix: Remove non-existing bookmarks.{export,import}
These APIs are not supported by Firefox:
https://searchfox.org/mozilla-central/rev/292d295d6b084b43b70de26a42e68513bb7b36a3/browser/components/extensions/schemas/bookmarks.json#436-465

In Chrome the APIs are not available either, except to some internal components:
b7963dca6a/chrome/common/extensions/api/_api_features.json (138)

Also moved "getTree" to ensure that the keys are alphabetically sorted.
2018-06-15 10:49:53 -07:00
Rob Wu 4a407da02c feat: Add topSites namespace to metadata
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/topSites#Browser_compatibility
2018-06-15 10:41:08 -07:00
Rob Wu 69e58761a5 feat: Add sessions namespace to metadata
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/sessions#Browser_compatibility

Only `sessions.getRecentlyClosed` and `sessions.restore` are currently
supported by Firefox.

`sessions.getDevices` is included anyway since this method may be added
to Firefox in the future: https://bugzil.la/1308059
2018-06-15 10:41:08 -07:00
Rob Wu f086bc15ac feat: Add permissions namespace to metadata
https://searchfox.org/mozilla-central/rev/292d295d6b084b43b70de26a42e68513bb7b36a3/toolkit/components/extensions/schemas/permissions.json
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/permissions#Browser_compatibility
2018-06-15 10:41:08 -07:00
Rob Wu 9225b2a91b feat: Add browsingData namespace to metadata
The auto-generated output from the metadata generator also includes the
following methods from Chrome. Firefox does not support them, so they
were not included in the metadata:

```
    "removeAppcache": {
      "minArgs": 1,
      "maxArgs": 1
    },
    "removeFileSystems": {
      "minArgs": 1,
      "maxArgs": 1
    },
    "removeIndexedDB": {
      "minArgs": 1,
      "maxArgs": 1
    },
    "removeWebSQL": {
      "minArgs": 1,
      "maxArgs": 1
    },
```

Also see:
https://searchfox.org/mozilla-central/rev/292d295d6b084b43b70de26a42e68513bb7b36a3/browser/components/extensions/schemas/browsing_data.json
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/browsingData#Browser_compatibility
2018-06-15 10:41:08 -07:00
Luca Greco 5d186bae84 test(browsers-smoketests): Run a set of smoke tests on both Chrome and Firefox
This commit introduces tape as the test framework used to define the tests in the
test extension contexts and send them to the nodejs script that orchestrate the
test run.

The nodejs script has also been migrated from mocha to tape, it uses the custom test
helpers provided to setup the test environment (e.g. create a temporary dir
for the test extension, copy the last polyfill build, bundle tape to be used
in the test extension, start the browser which run the test extension
and finally collect the results of the test extension) and then it merges all the
tap logs collected from every test extension into a single "per browser" test suite.

- updated travis nodejs environment to nodejs 8
- uses tape to collect test results from inside the test extension
- added test case to check polyfill 'existing browser API object' detection
- added test for expected rejection on tabs.sendMessage with an invalid tabId
- added test with multiple listeners which resolves to undefined and null
- optionally run chrome smoketests with --enable-features=NativeCrxBindings
2018-06-02 20:59:46 +02:00
Luca Greco 6c8268f6fb feat: Reject sendMessage returned promise when a onMessage listener returns a rejected promise. 2018-06-02 20:59:46 +02:00
Luca Greco 831e355650 fix: print a deprecation warning when sendResponse callback is used for the first time 2018-06-02 20:59:46 +02:00
YFdyh000 314d2c6df7 chore: Always use LF for dist files (#67) 2018-05-31 16:19:46 +02:00
Luca Greco 76eeeaccc9
feat: Added support for the sendResponse callback in the runtime.onMessage listeners (#97) 2018-05-14 20:38:21 +02:00
Federico Brigante 6f9cfdf6cf chore(README): Drop reference to babel for async/await (#50) 2018-04-09 19:24:15 +02:00
Rob Wu bdb07e10cc chore: Added .gitattributes to force eol=lf to fix #101 (#103) 2018-04-09 15:44:30 +02:00
Luca Greco dd180a0907 chore(test): Fixed module bundlers tests on webpack 4 2018-04-09 15:13:35 +02:00
Rob Wu a7cbdcc23e fix: Use browser.storage.local in README (#87) (#90)
Applied fixed to all code snippets in README.md so that they are syntactically valid.
2018-03-19 15:42:40 +01:00
Luca Greco 0fd508671a test: Added smoke test for pageAction.show fallback to no callback on chrome. 2018-03-13 14:27:22 +01:00
Gerben 596f47bcc8 chore: Improve "fallback to no callback" wrapper.
According to review comment https://github.com/mozilla/webextension-polyfill/pull/59/files#r142001949
2018-03-13 14:27:22 +01:00
Luca Greco 917ed413f6 fix: Add a new fallbackToNoCallback metadata property to customize the pageAction.show/hide wrappers behavior 2018-03-13 14:27:22 +01:00
Megaman 0778db93ca fix: pageAction.show/hide should have 1 non-optional parameter in their metadata 2018-03-13 14:27:22 +01:00
Rob Wu 67b3780d38 fix: Lazily initialize API via the original target (#71)
Originally, the polyfill created a Proxy with the original API object as
the target. This was changed to `Object.create(chrome)` because not
doing so would prevent the `browser.devtools` API from working because
the devtools API object is assigned as a read-only & non-configurable
property (#57).

However, that action itself caused a new bug: Whenever an API object
is dereferenced via the `browser` namespace, the original API is no
longer available in the `chrome` namespace, and trying to access the
API through `chrome` returns `undefined` plus the "Previous API
instantiation failed" warning (#58).
This is because Chrome lazily initializes fields in the `chrome`
API, but on the object from which the property is accessed, while
the polyfill accessed the property through an object with the
prototype set to `chrome` instead of directly via chrome.

To fix that, `Object.create(chrome)` was replaced with
`Object.assign({}, chrome)`. This fixes both of the previous issues
because
1) It is still a new object.
2) All lazily initialized fields are explicitly initialized.

This fix created a new issue: In Chrome some APIs cannot be used even
though they are visible in the API (e.g. `chrome.clipboard`), so
calling `Object.assign({}, chrome)` causes an error to be printed to
the console (#70).

To solve this, I use `Object.create(chrome)` again as a proxy target,
but dereference the API via the original target (`chrome`) to not
regress on #58.
Besides fixing the bug, this also reduces the performance impact
of the API because all API fields are lazily initialized again,
instead of upon start-up.

This fixes #70.
2018-03-12 19:23:28 +01:00
Luca Greco 94efb908b8
fix: Pass --no-sandbox chrome CLI option when running the integration tests on travis (#85) 2018-01-09 17:49:56 +01:00
Sébastien Règne 13d0ced89e feat: add identity.launchWebAuthFlow() in metadata. (#39)
Provides the api metadata for the identity.launchWebAuthFlow API method (which fixes #80)
2018-01-09 16:27:33 +01:00
Luca Greco 49ce6ef155 test: Run a minimal set of tests from a test extension running on Chrome (#66)
* test: Run a minimal set of integration/smoke tests on Chrome
* chore: minor tweaks to dependencies version in the package.json
2017-10-23 19:42:01 +02:00
Luca Greco 8914541b81 chore: bump version for release 0.2.1 2017-10-12 14:23:39 +02:00
Luca Greco 47ddfbfddb fix: Prevent 'Previous API instantiation failed' errors on runtime.sendMessage API calls (#64) 2017-10-11 15:51:43 +02:00
Andy McKay 09d05cc073 Merge pull request #62 from tiagomoraismorgado88/patch-1
introducing table of contents
2017-10-06 10:36:37 -07:00
tmm88 390ccbf8b6 introducing table of contents
# Greetings

**the current PR does basically aim at:**
- *introducing table of contents*

---

**the motivation behind such a thing is basically to:**
- *improve accessability of the file*
2017-10-01 11:47:50 +01:00
121 changed files with 16756 additions and 268 deletions

174
.circleci/config.yml Normal file
View File

@ -0,0 +1,174 @@
# These environment variables must be set in CircleCI UI
#
# NPM_TOKEN - A valid NPM token for releases
#
# NOTE:
# - to validate changes to this file locally using the circleci CLI tool:
#
# circleci config process .circleci/config.yml
#
# - to try run jobs locally:
#
# circleci config process .circleci/config.yml > tmp/processed.yml
# circleci local execute -c tmp/processed.yml --job build-nodejs-current
#
version: 2.1
orbs:
codecov: codecov/codecov@3.2.0
references:
nodejs_current: &nodejs_current "12"
repo_path: &repo_path ~/webextension-polyfill
defaults: &defaults
working_directory: *repo_path
parameters:
nodejs_current:
type: string
default: *nodejs_current
commands:
run_npm_install:
description: install npm dependencies
steps:
- run: npm i
run_npm_build:
description: build project in << parameters.node_env >> mode
parameters:
node_env:
type: enum
default: production
enum: ["production", "test"]
steps:
- run:
command: npm run build --if-present
environment:
NODE_ENV: << parameters.node_env >>
run_test_minified:
description: rerun unit tests on minified file
steps:
- run:
command: npm run test-minified
run_test_bundlers:
description: rerun unit tests on webpack and browserify bundled files
steps:
- configure_global_npm
- run: npm install -g browserify webpack webpack-cli
- run: |
export PATH=$PATH:../.npm-global/bin
node ./scripts/run-module-bundlers-smoketests.js
run_xephyr:
description: run Xephyr on DISPLAY=:10
steps:
- run: |
sudo apt update
sudo apt install xserver-xephyr
Xephyr -ac -br -noreset -screen 1280x1024x24 :10 &
sleep 2
run_functional_tests:
description: run integration tests on Firefox and Chrome browsers
steps:
# circleci browsers image variant does include and run Xvfb
# unfortunately Chrome seems to intermittently fail to connect
# to it successfully:
#
# ERROR:browser_main_loop.cc(1434)] Unable to open X display
#
# On the contrary it seems to don't happen with Xephyr.
- run_xephyr
- run:
command: node ./scripts/run-browsers-smoketests.js
environment:
DISPLAY: :10.0
CHROMEDRIVER_VERBOSE_LOGFILE: /tmp/chromedriver.log
- store_artifacts:
# chromedriver verbose logs stored in the artifacts to make
# it easier investigate CI jobs chromedriver issues.
path: /tmp/chromedriver.log
run_tests:
description: run tests
steps:
- run:
name: run linting check and unit tests with coverage
command: npm run test-coverage
environment:
COVERAGE_WITH_SOURCEMAP: "1"
- store_artifacts:
path: coverage
- codecov/upload
- run_test_minified
- run_test_bundlers
- run_functional_tests
# This is required to avoid a `EACCES` when running `npm install -g` (which is
# executed in the test suite).
configure_global_npm:
description: create custom directory for global npm installs
steps:
- run: mkdir ../.npm-global
- run: npm config set prefix '../.npm-global'
attach_project_repo:
description: attach repo from workspace
steps:
- attach_workspace:
at: *repo_path
persist_project_repo:
description: persist repo in workspace
steps:
- persist_to_workspace:
root: *repo_path
paths: .
jobs:
build:
<<: *defaults
docker:
# Image variant including Firefox, Chrome and Xvfb
- image: circleci/node:<< parameters.nodejs_current >>-browsers
steps:
- attach_project_repo
- checkout
- run_npm_install
- run_npm_build:
node_env: test
- run_tests
- persist_project_repo
release-tag:
<<: *defaults
docker:
- image: circleci/node:<< parameters.nodejs_current >>
steps:
- attach_project_repo
- run_npm_build:
node_env: production
- run:
name: npm registry auth
command: echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > .npmrc
- run:
name: npm registry publish
command: npm publish
workflows:
default-workflow:
jobs:
- build:
name: build-nodejs-current
filters:
tags:
only: /.*/
- release-tag:
requires:
- build-nodejs-current
filters:
tags:
only: /.*/
branches:
ignore: /.*/

11
.editorconfig Normal file
View File

@ -0,0 +1,11 @@
root = true
[*]
end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true
[*.{eslintrc,html,js,json,md}]
indent_style = space
indent_size = 2

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
coverage/
dist/

View File

@ -1,16 +1,19 @@
{
"root": true,
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
},
"env": {
"browser": true,
"es6": true,
"webextensions": true,
"node": true,
},
"globals": {
"globalThis": true,
},
"rules": {
@ -413,7 +416,7 @@
"quote-props": 0,
// Double quotes should be used.
"quotes": [1, "double", {"avoidEscape": true, "allowTemplateLiterals": true}],
"quotes": [2, "double", {"avoidEscape": true, "allowTemplateLiterals": true}],
// Require use of the second argument for parseInt().
"radix": 2,
@ -429,7 +432,7 @@
"spaced-comment": [2, "always"],
// Require "use strict" to be defined globally in the script.
"strict": [2, "global"],
"strict": [0, "global"],
// Allow vars to be declared anywhere in the scope.
"vars-on-top": 0,

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
*.js text eol=lf
*.json text eol=lf

View File

@ -1,36 +0,0 @@
language: node_js
sudo: false
node_js:
## Some of the ES6 syntax used in the browser-polyfill sources is only supported on nodejs >= 6
- '6'
script:
- npm run build
- npm run test-coverage
- echo "RE-RUN tests on the minified file" && npm run test-minified
- echo "RE-RUN tests on the webpack and browserify bundled files" &&
npm install -g browserify webpack &&
./test/run-module-bundlers-smoketests.sh
after_script: npm run publish-coverage
notifications:
irc:
channels:
- irc.mozilla.org#webextensions
on_success: change
on_failure: always
use_notice: true
template:
- "%{repository}#%{build_number} (%{branch} - %{commit} : %{author}): %{message} (%{build_url})"
deploy:
provider: npm
email: addons-dev-automation+npm@mozilla.com
skip_cleanup: true
on:
tags: true
repo: mozilla/webextension-polyfill
branch: master
api_key:
secure: W1e/XXtsl98NGUYsqlELnrspPW/ULUk74dUMmLC7iqmI8RVvzBgjkxBGmgsToZAbdzeNMlsOeeNz2iF+DSy3UF9bc3PTdHmN8kYU8enqo3P/FKK29rg5udx/HRW2GK06UzEBctOY90OwnUD+J1OaCJ0vMh6EekiP1BXOtrvch6Ruo7SYrwQ0vu5gFM+ifwfpGycTbRd77P6YJzbxYSEJfkQz1R1X7i8pLmi0vTyQa3tUYsQd8WzL6CJsWitojtf0FHGJgzXu2g6iFmkLVC0+dnGCRAxnRbixoYMmJYyEcvgIXlmNB6gl7ortuWKOp82lhXWXZWaYqO9Y8w4X0I8iNQzrLnupwyaC0cK51OPLLZEdgXa+bXmsYi2LYiV72oTCFd7j+f8hcoPOtgkGXJR+5F87zZLy8Ayr62fshWE/sl+dw2b/H5AqER4UNlX1+EiHQHjUtSvYlAmkTX3t4q/c+d0T1U5aM0CbOhS5juYVVqyIFGlUoRdNKDVedn0uCd+D2ItGj9y7yex0z+tc8iKaze0DhQCMq5QTxEU89REEU7Bf3gkpZtXlcmGZX/RTTCe941is7cIrUeJrZXPt5lA+cudBf3t60t7qysHLconQ+TXlDxCBvX7lLF9lZT5z0BKdOA0iL574ABtiJEjPxi0gOIWg2DJh15OZGA5mC4gPsZ4=

10
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,10 @@
# Community Participation Guidelines
This repository is governed by Mozilla's code of conduct and etiquette guidelines.
For more details, please read the
[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
## How to Report
For more information on how to report violations of the Community Participation Guidelines,
please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.

106
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,106 @@
Hi! Thanks for your interest in helping to make the "cross-browser extension" developers life easier by contributing to the `webextension-polyfill` library.
This document provides some additional information that you may find useful while looking at how to apply changes to this library and submit them for review.
Table of contents
=================
* [Building](#building)
* [Test Suites](#test-suites)
* [Writing commit messages](#writing-commit-messages)
## Building
To build, assuming you've already installed [node >= 6](https://nodejs.org) and
[npm](https://www.npmjs.com/), simply run:
```sh
git clone https://github.com/mozilla/webextension-polyfill.git
cd webextension-polyfill
npm install
npm run test
```
This will install all the npm dependencies and build both non-minified and minified versions
of the final library, and output them to `dist/browser-polyfill.js` and `dist/browser-polyfill.min.js`,
respectively, and finally execute the unit tests on the generated dist files.
## Test Suites
This project provides two test suites:
- unit tests (which only require Node.js to run)
- module bundlers smoke tests (which requires also browserify and webpack to be installed globally)
- integration tests (which requires also a stable version of Chrome and Firefox)
### Unit Tests
The unit tests run in Node.js with [Mocha](https://mochajs.org), and use jsdom and
[Sinon](https://sinonjs.org) to mock a browser-like environment for testing the library.
The unit tests are located in the `"test/"` directory and they have to be named `"test/test-*.js"`.
`npm run test` run all the unit tests on the non-minified version of the library,
whereas `npm run test-minified` can be used to run the unit tests on the minified version.
Optionally code coverage data can be collected and reported while running the unit tests,
by running `npm run test-coverage`.
### Module Bundler smoketests
The shell script `test/run-module-bundlers-smoketests.sh` runs browserify and webpack,
to verify that the most commonly used module bundlers are not raising any unexpected error
while building a bundle that requires this library.
### Integration Tests
This repository also includes a small set of integration tests, located at `"test/integration/"`.
The integration tests use selenium-webdriver to run a set of test extensions
(located at `"test/fixtures/"`) on real browsers, currently Chrome (as the browser officially
supported by this library) and Firefox (to compare the polyfilled APIs with the ones natively
provided on Firefox).
The shell script `test/run-browsers-smoketests.sh` (executed by the CI service on every
pull request) runs this test suite on both the browsers.
To run the integration tests on a single browser:
```sh
TEST_BROWSER_TYPE=chrome npm run test-integration
```
or
```sh
TEST_BROWSER_TYPE=firefox npm run test-integration
```
These tests emit their results using the TAP protocol. To get a nicer output on the console
you may want to pipe the results to `tap-nirvana`, e.g.
```sh
TEST_BROWSER_TYPE=chrome npm run test-integration | ./node_modules/.bin/tap-nirvana
```
## Writing commit messages
The subject of the pull requests and commit messages must adhere to the Angular style of
[semantic messages](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#commits).
This allows us to auto-generate a changelog without too much noise in it.
Additionally, write the commit message in past tense so it will read
naturally as a historic changelog.
Examples:
* `feat: Added newAmazingAPI namespace to the metadata`
* `fix: newAmazingAPI.create should reject on errors`
* `docs: Improved contributor docs`
* `style: Added no-console linting, cleaned up code`
* `refactor: Split out myHelperFunction`
* `perf: Changed myHelperFunction to be 2x faster`
* `test: Added more tests for newAmazingAPI`
* `chore: Upgraded yargs to 3.x.x`
If you want to use scopes then it would look more like:
`test(integration): Added test extension for newAmazingAPI`.

View File

@ -2,27 +2,19 @@
/* vim: set sts=2 sw=2 et tw=80: */
"use strict";
/* eslint-env commonjs */
const LICENSE = `/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */`;
const MINIFIED_FILE_FOOTER = `\n\n// <%= pkg.name %> v.<%= pkg.version %> (<%= pkg.homepage %>)\n\n${LICENSE}`;
const MINIFIED_FILE_FOOTER = `\n// <%= pkg.name %> v.<%= pkg.version %> (<%= pkg.homepage %>)\n\n${LICENSE}\n`;
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
coveralls: {
all: {
src: "coverage/lcov.info",
},
},
eslint: {
src: ["src/browser-polyfill.js", "Gruntfile.js"],
test: ["test/**/*.js"],
test: ["test/**/*.js", "scripts/**/*.js"],
},
replace: {
@ -62,7 +54,7 @@ module.exports = function(grunt) {
options: {
babelrc: false,
comments: false,
presets: ["babili"],
presets: ["minify"],
sourceMap: true,
},
files: {
@ -74,11 +66,9 @@ module.exports = function(grunt) {
babelrc: false,
comments: true,
plugins: [
["transform-es2015-modules-umd", {
globals: {
"webextension-polyfill": "browser",
},
exactGlobals: true,
["./scripts/babel-transform-to-umd-module", {
globalName: "browser",
amdModuleName: "webextension-polyfill",
}],
],
sourceMap: true,
@ -99,9 +89,10 @@ module.exports = function(grunt) {
},
});
grunt.util.linefeed = "\n";
grunt.loadNpmTasks("gruntify-eslint");
grunt.loadNpmTasks("grunt-replace");
grunt.loadNpmTasks("grunt-coveralls");
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-babel");

268
README.md
View File

@ -1,32 +1,80 @@
# WebExtension `browser` API Polyfill [![Build Status](https://travis-ci.org/mozilla/webextension-polyfill.svg?branch=master)](https://travis-ci.org/mozilla/webextension-polyfill)
# WebExtension `browser` API Polyfill
This library allows extensions written for the Promise-based
WebExtension/BrowserExt API being standardized by the [W3 Browser
Extensions][w3-browserext] group to be used without modification in Google
Chrome.
This library allows extensions that use the Promise-based WebExtension/BrowserExt API being standardized by the
[W3 Browser Extensions][w3-browserext] group to run on Google Chrome with minimal or no changes.
[![CircleCI](https://circleci.com/gh/mozilla/webextension-polyfill.svg?style=svg)](https://circleci.com/gh/mozilla/webextension-polyfill)
[![codecov](https://codecov.io/gh/mozilla/webextension-polyfill/branch/master/graph/badge.svg)](https://codecov.io/gh/mozilla/webextension-polyfill)
[![devDependency Status](https://david-dm.org/mozilla/webextension-polyfill/dev-status.svg)](https://david-dm.org/mozilla/webextension-polyfill#info=devDependencies)
[![npm version](https://badge.fury.io/js/webextension-polyfill.svg)](https://badge.fury.io/js/webextension-polyfill)
> This library doesn't (and it is not going to) polyfill API methods or options that are missing on Chrome but natively provided
> on Firefox, and so the extension has to do its own "runtime feature detection" in those cases (and then eventually polyfill the
> missing feature on its own or enable/disable some of the features accordingly).
[w3-browserext]: https://www.w3.org/community/browserext/
## Building
Table of contents
=================
To build, assuming you're already installed [node >= 6](https://nodejs.org) and
[npm](https://www.npmjs.com/), simply run:
* [Supported Browsers](#supported-browsers)
* [Installation](#installation)
* [Basic Setup](#basic-setup)
* [Basic Setup with ES6 module loader](#basic-setup-with-es6-module-loader)
* [Basic Setup with module bundlers](#basic-setup-with-module-bundlers)
* [Usage with webpack without bundling](#usage-with-webpack-without-bundling)
* [Using the Promise-based APIs](#using-the-promise-based-apis)
* [Examples](#examples)
* [Usage with TypeScript](#usage-with-typescript)
* [Known Limitations and Incompatibilities](#known-limitations-and-incompatibilities)
* [Contributing to this project](#contributing-to-this-project)
```sh
npm install
npm run build
npm run test
Supported Browsers
==================
| Browser | Support Level |
| ------------------------- | -------------------------------------------------------------------------------------------------- |
| Chrome | *Officially Supported* (with automated tests) |
| Firefox | *Officially Supported as a NO-OP* (with automated tests for comparison with the behaviors on Chrome) |
| Opera / Edge (>=79.0.309) | *Unofficially Supported* as a Chrome-compatible target (but not explicitly tested in automation) |
The polyfill is being tested explicitly (with automated tests that run on every pull request) on **officially supported**
browsers (that are currently the last stable versions of Chrome and Firefox).
On Firefox, this library is actually acting as a NO-OP: it detects that the `browser` API object is already defined
and it does not create any custom wrappers.
Firefox is still included in the automated tests, to ensure that no wrappers are being created when running on Firefox,
and for comparison with the behaviors implemented by the library on Chrome.
## Installation
A new version of the library is built from this repository and released as an npm package.
The npm package is named after this repo: [webextension-polyfill](https://www.npmjs.com/package/webextension-polyfill).
For the extension that already include a package.json file, the last released version of this library can be quickly installed using:
```
npm install --save-dev webextension-polyfill
```
This will install all the npm dependencies and build both non-minified and minified versions
of the final library, and output them to `dist/browser-polyfill.js` and `dist/browser-polyfill.min.js`,
respectively, and finally executes the unit tests on the generated dist files.
Inside the `dist/` directory of the npm package, there are both the minified and non-minified builds (and their related source map files):
- node_modules/webextension-polyfill/dist/browser-polyfill.js
- node_modules/webextension-polyfill/dist/browser-polyfill.min.js
For extensions that do not include a package.json file and/or prefer to download and add the library directly into their own code repository, all the versions released on npm are also available for direct download from unpkg.com:
- https://unpkg.com/webextension-polyfill/dist/
and linked to the Github releases:
- https://github.com/mozilla/webextension-polyfill/releases
## Basic Setup
In order to use the polyfill, it must be loaded into any context where
`browser` APIs are accessed. The most common cases are background and
content scripts, which can be specified in `manifest.json`:
In order to use the polyfill, it must be loaded into any context where `browser` APIs are accessed. The most common cases
are background and content scripts, which can be specified in `manifest.json` (make sure to include the `browser-polyfill.js` script before any other scripts that use it):
```javascript
{
@ -75,6 +123,102 @@ browser.tabs.executeScript({file: "content.js"}).then(result => {
});
```
### Basic Setup with ES6 module loader
The polyfill can also be loaded using the native ES6 module loader available in
the recent browsers versions.
Be aware that the polyfill module does not export the `browser` API object,
but defines the `browser` object in the global namespace (i.e. `window`).
```html
<!DOCTYPE html>
<html>
<head>
<script type="module" src="browser-polyfill.js"></script>
<script type="module" src="background.js"></script>
</head>
<!-- ... -->
</html>
```
```javascript
// In background.js (loaded after browser-polyfill.js) the `browser`
// API object is already defined and provides the promise-based APIs.
browser.runtime.onMessage.addListener(...);
```
### Basic Setup with module bundlers
This library is built as a **UMD module** (Universal Module Definition), and so it can also be used with module bundlers (and explicitly tested on both **webpack** and **browserify**) or AMD module loaders.
**src/background.js**:
```javascript
var browser = require("webextension-polyfill");
browser.runtime.onMessage.addListener(async (msg, sender) => {
console.log("BG page received message", msg, "from", sender);
console.log("Stored data", await browser.storage.local.get());
});
browser.browserAction.onClicked.addListener(() => {
browser.tabs.executeScript({file: "content.js"});
});
```
**src/content.js**:
```javascript
var browser = require("webextension-polyfill");
browser.storage.local.set({
[window.location.hostname]: document.title,
}).then(() => {
browser.runtime.sendMessage(`Saved document title for ${window.location.hostname}`);
});
```
By using `require("webextension-polyfill")`, the module bundler will use the non-minified version of this library, and the extension is supposed to minify the entire generated bundles as part of its own build steps.
If the extension doesn't minify its own sources, it is still possible to explicitly ask the module bundler to use the minified version of this library, e.g.:
```javascript
var browser = require("webextension-polyfill/dist/browser-polyfill.min");
...
```
### Usage with webpack without bundling
The previous section explains how to bundle `webextension-polyfill` in each script. An alternative method is to include a single copy of the library in your extension, and load the library as shown in [Basic Setup](#basic-setup). You will need to install [copy-webpack-plugin](https://www.npmjs.com/package/copy-webpack-plugin):
```sh
npm install --save-dev copy-webpack-plugin
```
**In `webpack.config.js`,** import the plugin and configure it this way. It will copy the minified file into your _output_ folder, wherever your other webpack files are generated.
```js
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
/* Your regular webpack config, probably including something like this:
output: {
path: path.join(__dirname, 'distribution'),
filename: '[name].js'
},
*/
plugins: [
new CopyWebpackPlugin({
patterns: [{
from: 'node_modules/webextension-polyfill/dist/browser-polyfill.js',
}],
})
]
}
```
And then include the file in each context, using the `manifest.json` just like in [Basic Setup](#basic-setup).
## Using the Promise-based APIs
The Promise-based APIs in the `browser` namespace work, for the most part,
@ -95,9 +239,8 @@ The major differences are:
* Rather than nesting callbacks when a sequence of operations depend on each
other, Promise chaining is generally used instead.
* For users of an ES7 transpiler, such as Babel, the resulting Promises are
generally used with `async` and `await`, rather than dealt with
directly.
* The resulting Promises can be also used with `async` and `await`, rather
than dealt with directly.
## Examples
@ -106,11 +249,11 @@ API, retrieve a list of tabs which match any of them, reload each of those
tabs, and notify the user that is has been done:
```javascript
browser.storage.get("urls").then(({urls}) => {
browser.storage.local.get("urls").then(({urls}) => {
return browser.tabs.query({url: urls});
}).then(tabs => {
return Promise.all(
Array.from(tabs, tab => browser.tabs.reload(tab.id)));
Array.from(tabs, tab => browser.tabs.reload(tab.id))
);
}).then(() => {
return browser.notifications.create({
@ -129,12 +272,12 @@ Or, using an async function:
```javascript
async function reloadTabs() {
try {
let {urls} = await browser.storage.get("urls");
let {urls} = await browser.storage.local.get("urls");
let tabs = await browser.tabs.query({url: urls});
await Promise.all(
Array.from(tabs, tab => browser.tabs.reload(tab.id)));
Array.from(tabs, tab => browser.tabs.reload(tab.id))
);
await browser.notifications.create({
@ -154,7 +297,7 @@ Communication between a background page and a tab content script, for example,
looks something like this from the background page side:
```javascript
browser.tabs.sendMessage("get-ids").then(results => {
browser.tabs.sendMessage(tabId, "get-ids").then(results => {
processResults(results);
});
```
@ -164,7 +307,7 @@ And like this from the content script:
```javascript
browser.runtime.onMessage.addListener(msg => {
if (msg == "get-ids") {
return browser.storage.get("idPattern").then(({idPattern}) => {
return browser.storage.local.get("idPattern").then(({idPattern}) => {
return Array.from(document.querySelectorAll(idPattern),
elem => elem.textContent);
});
@ -177,7 +320,7 @@ or:
```javascript
browser.runtime.onMessage.addListener(async function(msg) {
if (msg == "get-ids") {
let {idPattern} = await browser.storage.get("idPattern");
let {idPattern} = await browser.storage.local.get("idPattern");
return Array.from(document.querySelectorAll(idPattern),
elem => elem.textContent);
@ -186,3 +329,72 @@ browser.runtime.onMessage.addListener(async function(msg) {
```
Or vice versa.
## Usage with TypeScript
There are multiple projects that add TypeScript support to your web-extension project:
| Project | Description |
| ------------- | ------------- |
| [@types/webextension-polyfill](https://www.npmjs.com/package/@types/webextension-polyfill) | Types and JS-Doc are automatically generated from the mozilla schema files, so it is always up-to-date with the latest APIs. Formerly known as [webextension-polyfill-ts](https://github.com/Lusito/webextension-polyfill-ts). |
| [web-ext-types](https://github.com/kelseasy/web-ext-types) | Manually maintained types based on MDN's documentation. No JS-Doc included. |
| [@types/chrome](https://www.npmjs.com/package/@types/chrome) | Manually maintained types and JS-Doc. Only contains types for chrome extensions though! |
## Known Limitations and Incompatibilities
This library tries to minimize the amount of "special handling" that a cross-browser extension has to do to be able to run on the supported browsers from a single codebase, but there are still cases when polyfillling the missing or incompatible behaviors or features is not possible or out of the scope of this polyfill.
This section aims to keep track of the most common issues that an extension may have.
### No callback supported by the Promise-based APIs on Chrome
While some of the asynchronous API methods in Firefox (the ones that return a promise) also support the callback parameter (mostly as a side effect of the backward compatibility with the callback-based APIs available on Chrome), the Promise-based APIs provided by this library do not support the callback parameter (See ["#102 Cannot call browser.storage.local.get with callback"][I-102]).
### No promise returned on Chrome for some API methods
This library takes its knowledge of the APIs to wrap and their signatures from a metadata JSON file:
[api-metadata.json](api-metadata.json).
If an API method is not yet included in this "API metadata" file, it will not be recognized.
Promises are not supported for unrecognized APIs, and callbacks have to be used for them.
Chrome-only APIs have no promise version, because extensions that use such APIs
would not be compatible with Firefox.
File an issue in this repository for API methods that support callbacks in Chrome *and*
Firefox but are currently missing from the "API metadata" file.
### Issues that happen only when running on Firefox
When an extension that uses this library doesn't behave as expected on Firefox, it is almost never an issue in this polyfill, but an issue with the native implementation in Firefox.
"Firefox only" issues should be reported upstream on Bugzilla:
- https://bugzilla.mozilla.org/enter_bug.cgi?product=WebExtensions&component=Untriaged
### API methods or options that are only available when running in Firefox
This library does not provide any polyfill for API methods and options that are only available on Firefox, and they are actually considered out of the scope of this library.
### tabs.executeScript
On Firefox `browser.tabs.executeScript` returns a promise which resolves to the result of the content script code that has been executed, which can be an immediate value or a Promise.
On Chrome, the `browser.tabs.executeScript` API method as polyfilled by this library also returns a promise which resolves to the result of the content script code, but only immediate values are supported.
If the content script code result is a Promise, the promise returned by `browser.tabs.executeScript` will be resolved to `undefined`.
### MSEdge support
MSEdge versions >= 79.0.309 are unofficially supported as a Chrome-compatible target (as for Opera or other Chrome-based browsers that also support extensions).
MSEdge versions older than 79.0.309 are **unsupported**, for extension developers that still have to work on extensions for older MSEdge versions, the MSEdge `--ms-preload` manifest key and the [Microsoft Edge Extension Toolkit](https://docs.microsoft.com/en-us/microsoft-edge/extensions/guides/porting-chrome-extensions)'s Chrome API bridge can be used to be able to load the webextension-polyfill without any MSEdge specific changes.
The following Github repository provides some additional detail about this strategy and a minimal test extension that shows how to put it together:
- https://github.com/rpl/example-msedge-extension-with-webextension-polyfill
## Contributing to this project
Read the [contributing section](CONTRIBUTING.md) for additional information about how to build the library from this repository and how to contribute and test changes.
[PR-114]: https://github.com/mozilla/webextension-polyfill/pull/114
[I-102]: https://github.com/mozilla/webextension-polyfill/issues/102#issuecomment-379365343

View File

@ -22,10 +22,6 @@
"minArgs": 1,
"maxArgs": 1
},
"export": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 1,
"maxArgs": 1
@ -38,15 +34,11 @@
"minArgs": 1,
"maxArgs": 1
},
"getTree": {
"minArgs": 0,
"maxArgs": 0
},
"getSubTree": {
"minArgs": 1,
"maxArgs": 1
},
"import": {
"getTree": {
"minArgs": 0,
"maxArgs": 0
},
@ -72,6 +64,16 @@
}
},
"browserAction": {
"disable": {
"minArgs": 0,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"enable": {
"minArgs": 0,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"getBadgeBackgroundColor": {
"minArgs": 1,
"maxArgs": 1
@ -88,9 +90,75 @@
"minArgs": 1,
"maxArgs": 1
},
"openPopup": {
"minArgs": 0,
"maxArgs": 0
},
"setBadgeBackgroundColor": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setBadgeText": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
},
"setPopup": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setTitle": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"browsingData": {
"remove": {
"minArgs": 2,
"maxArgs": 2
},
"removeCache": {
"minArgs": 1,
"maxArgs": 1
},
"removeCookies": {
"minArgs": 1,
"maxArgs": 1
},
"removeDownloads": {
"minArgs": 1,
"maxArgs": 1
},
"removeFormData": {
"minArgs": 1,
"maxArgs": 1
},
"removeHistory": {
"minArgs": 1,
"maxArgs": 1
},
"removeLocalStorage": {
"minArgs": 1,
"maxArgs": 1
},
"removePasswords": {
"minArgs": 1,
"maxArgs": 1
},
"removePluginData": {
"minArgs": 1,
"maxArgs": 1
},
"settings": {
"minArgs": 0,
"maxArgs": 0
}
},
"commands": {
@ -100,10 +168,6 @@
}
},
"contextMenus": {
"update": {
"minArgs": 2,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
@ -111,6 +175,10 @@
"removeAll": {
"minArgs": 0,
"maxArgs": 0
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"cookies": {
@ -139,7 +207,8 @@
"inspectedWindow": {
"eval": {
"minArgs": 1,
"maxArgs": 2
"maxArgs": 2,
"singleCallbackArg": false
}
},
"panels": {
@ -147,15 +216,21 @@
"minArgs": 3,
"maxArgs": 3,
"singleCallbackArg": true
},
"elements": {
"createSidebarPane": {
"minArgs": 1,
"maxArgs": 1
}
}
}
},
"downloads": {
"download": {
"cancel": {
"minArgs": 1,
"maxArgs": 1
},
"cancel": {
"download": {
"minArgs": 1,
"maxArgs": 1
},
@ -169,7 +244,8 @@
},
"open": {
"minArgs": 1,
"maxArgs": 1
"maxArgs": 1,
"fallbackToNoCallback": true
},
"pause": {
"minArgs": 1,
@ -189,7 +265,8 @@
},
"show": {
"minArgs": 1,
"maxArgs": 1
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"extension": {
@ -207,10 +284,6 @@
"minArgs": 1,
"maxArgs": 1
},
"getVisits": {
"minArgs": 1,
"maxArgs": 1
},
"deleteAll": {
"minArgs": 0,
"maxArgs": 0
@ -223,6 +296,10 @@
"minArgs": 1,
"maxArgs": 1
},
"getVisits": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
@ -238,6 +315,12 @@
"maxArgs": 0
}
},
"identity": {
"launchWebAuthFlow": {
"minArgs": 1,
"maxArgs": 1
}
},
"idle": {
"queryState": {
"minArgs": 1,
@ -257,6 +340,10 @@
"minArgs": 0,
"maxArgs": 0
},
"setEnabled": {
"minArgs": 2,
"maxArgs": 2
},
"uninstallSelf": {
"minArgs": 0,
"maxArgs": 1
@ -294,16 +381,46 @@
"maxArgs": 1
},
"hide": {
"minArgs": 0,
"maxArgs": 0
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
},
"setPopup": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setTitle": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"show": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"permissions": {
"contains": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"request": {
"minArgs": 1,
"maxArgs": 1
}
},
"runtime": {
@ -311,10 +428,6 @@
"minArgs": 0,
"maxArgs": 0
},
"getBrowserInfo": {
"minArgs": 0,
"maxArgs": 0
},
"getPlatformInfo": {
"minArgs": 0,
"maxArgs": 0
@ -340,6 +453,20 @@
"maxArgs": 1
}
},
"sessions": {
"getDevices": {
"minArgs": 0,
"maxArgs": 1
},
"getRecentlyClosed": {
"minArgs": 0,
"maxArgs": 1
},
"restore": {
"minArgs": 0,
"maxArgs": 1
}
},
"storage": {
"local": {
"clear": {
@ -397,18 +524,22 @@
}
},
"tabs": {
"create": {
"minArgs": 1,
"maxArgs": 1
},
"captureVisibleTab": {
"minArgs": 0,
"maxArgs": 2
},
"create": {
"minArgs": 1,
"maxArgs": 1
},
"detectLanguage": {
"minArgs": 0,
"maxArgs": 1
},
"discard": {
"minArgs": 0,
"maxArgs": 1
},
"duplicate": {
"minArgs": 1,
"maxArgs": 1
@ -433,6 +564,14 @@
"minArgs": 0,
"maxArgs": 1
},
"goBack": {
"minArgs": 0,
"maxArgs": 1
},
"goForward": {
"minArgs": 0,
"maxArgs": 1
},
"highlight": {
"minArgs": 1,
"maxArgs": 1
@ -445,6 +584,10 @@
"minArgs": 2,
"maxArgs": 2
},
"query": {
"minArgs": 1,
"maxArgs": 1
},
"reload": {
"minArgs": 0,
"maxArgs": 2
@ -453,10 +596,6 @@
"minArgs": 1,
"maxArgs": 1
},
"query": {
"minArgs": 1,
"maxArgs": 1
},
"removeCSS": {
"minArgs": 1,
"maxArgs": 2
@ -478,6 +617,12 @@
"maxArgs": 2
}
},
"topSites": {
"get": {
"minArgs": 0,
"maxArgs": 0
}
},
"webNavigation": {
"getAllFrames": {
"minArgs": 1,

View File

@ -1,10 +1,11 @@
{
"name": "webextension-polyfill",
"version": "0.2.0",
"name": "@lumeweb/webextension-polyfill",
"version": "0.8.0",
"description": "A lightweight polyfill library for Promise-based WebExtension APIs in Chrome.",
"main": "dist/browser-polyfill.js",
"main": "src/browser-polyfill.js",
"types": "types/index.d.ts",
"files": [
"dist"
"api-metadata.json"
],
"repository": {
"type": "git",
@ -17,21 +18,36 @@
},
"homepage": "https://github.com/mozilla/webextension-polyfill",
"devDependencies": {
"babel-plugin-transform-es2015-modules-umd": "^6.24.1",
"babel-preset-babili": "0.0.10",
"chai": "^3.5.0",
"eslint": "3.9.1",
"grunt": "^1.0.1",
"grunt-babel": "^6.0.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-coveralls": "^1.0.1",
"grunt-replace": "^1.0.1",
"gruntify-eslint": "^4.0.0",
"istanbul-lib-instrument": "^1.1.3",
"jsdom": "^9.6.0",
"mocha": "^3.1.0",
"nyc": "^8.3.1",
"sinon": "^1.17.6"
"@babel/core": "7.14.0",
"@babel/preset-env": "7.14.1",
"@babel/register": "7.13.16",
"babel-eslint": "10.1.0",
"babel-preset-minify": "0.5.1",
"browserify": "17.0.0",
"chai": "4.3.4",
"chromedriver": "96.0.0",
"cross-env": "7.0.3",
"eslint": "7.25.0",
"finalhandler": "1.1.2",
"geckodriver": "1.22.3",
"global-replaceify": "1.0.0",
"grunt": "1.4.0",
"grunt-babel": "8.0.0",
"grunt-contrib-concat": "1.0.1",
"grunt-replace": "2.0.2",
"gruntify-eslint": "5.0.0",
"istanbul-lib-instrument": "4.0.3",
"jsdom": "9.12.0",
"mocha": "8.4.0",
"nyc": "15.1.0",
"selenium-webdriver": "4.0.0-alpha.8",
"serve-static": "1.14.1",
"shelljs": "0.8.5",
"sinon": "10.0.0",
"tap-nirvana": "1.1.0",
"tape": "5.2.2",
"tape-async": "2.3.0",
"tmp": "0.2.1"
},
"nyc": {
"reporter": [
@ -43,10 +59,12 @@
},
"scripts": {
"build": "grunt",
"prepublish": "npm run build && npm run test",
"publish-coverage": "grunt coveralls",
"prepublish": "",
"test": "mocha",
"test-coverage": "COVERAGE=y nyc mocha",
"test-minified": "TEST_MINIFIED_POLYFILL=1 mocha"
"test-coverage": "cross-env COVERAGE=y nyc mocha",
"test-minified": "cross-env TEST_MINIFIED_POLYFILL=1 mocha",
"test-integration": "tape test/integration/test-*",
"test-integration:chrome": "cross-env TEST_BROWSER_TYPE=chrome npm run test-integration | tap-nirvana",
"test-integration:firefox": "cross-env TEST_BROWSER_TYPE=firefox npm run test-integration | tap-nirvana"
}
}

5
renovate.json Normal file
View File

@ -0,0 +1,5 @@
{
"extends": [
"config:base"
]
}

View File

@ -0,0 +1,61 @@
const {template, types} = require("@babel/core");
const buildWrapper = template(`
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(AMD_MODULE_NAME, ["module"], factory);
} else if (typeof exports !== "undefined") {
factory(module);
} else {
var mod = { exports: {} };
factory(mod);
global.GLOBAL = mod.exports;
}
})(
typeof globalThis !== "undefined" ? globalThis
: typeof self !== "undefined" ? self
: this,
function(module) {
}
)
`);
module.exports = (api, options = {}) => {
api.assertVersion(7);
if (typeof options.globalName != "string") {
throw new Error("globalName option is mandatory");
}
if (typeof options.amdModuleName != "string") {
throw new Error("amdModuleName is mandatory");
}
return {
name: "transform-to-umd-module",
visitor: {
Program: {
exit(path) {
const {body, directives} = path.node;
path.node.directives = [];
path.node.body = [];
const umdWrapper = path.pushContainer(
"body",
buildWrapper({
AMD_MODULE_NAME: types.stringLiteral(options.amdModuleName),
GLOBAL: options.globalName,
})
)[0];
const umdFactory = umdWrapper
.get("expression.arguments")[1]
.get("body");
umdFactory.pushContainer("directives", directives);
umdFactory.pushContainer("body", body);
},
},
},
};
};

View File

@ -0,0 +1,28 @@
#!/usr/bin/env node
"use strict";
const shell = require("shelljs");
/**
* This is to make sure that even if the tests fail on Chrome,
* the tests still run on Firefox, so that it can be seen whether
* Firefox broke too or is unaffected.
*/
let result = 0;
console.log(`
Test webextension-polyfill on real browsers
===========================================`);
// Enable headless mode (currently only used when running on Firefox
// because Chrome doesn't currently support the extensions in headless mode)
process.env.HEADLESS = 1;
console.log("\nRunning smoketests on Chrome");
process.env.TEST_BROWSER_TYPE = "chrome";
result = shell.exec("npm run test-integration:chrome").code || result;
console.log("\nRunning smoketests on Firefox");
process.env.TEST_BROWSER_TYPE = "firefox";
result = shell.exec("npm run test-integration:firefox").code || result;
process.exit(result);

View File

@ -0,0 +1,26 @@
#!/usr/bin/env node
const path = require("path");
const shell = require("shelljs");
let result = 0;
console.log(`
Test webextension-polyfill bundled with webpack
===============================================`);
process.env.TEST_BUNDLED_POLYFILL = "/tmp/webpack-bundle.js";
const webpackOutputDir = path.dirname(process.env.TEST_BUNDLED_POLYFILL);
const webpackOutputFilename = path.basename(process.env.TEST_BUNDLED_POLYFILL);
result = shell.exec(`webpack --mode production --entry ./test/fixtures/bundle-entrypoint.js --output-path ${webpackOutputDir} --output-filename ${webpackOutputFilename}`).code ||
shell.exec("npm run test").code || result;
console.log(`
Test webextension-polyfill bundled with browserify
==================================================`);
process.env.TEST_BUNDLED_POLYFILL = "/tmp/browserify-bundle.js";
result = shell.exec(`browserify test/fixtures/bundle-entrypoint.js > ${process.env.TEST_BUNDLED_POLYFILL}`).code ||
shell.exec("npm run test").code || result;
process.exit(result);

14
src/.eslintrc Normal file
View File

@ -0,0 +1,14 @@
{
"env": {
"browser": true,
"node": false,
// Don't use `webextensions` because it enables the browser global.
// We want to use globalThis.browser instead:
// https://github.com/mozilla/webextension-polyfill/pull/351
},
"globals": {
// Allow the `module` global, but not the `require(…)` function
"module": false,
"chrome": true,
},
}

View File

@ -1,23 +1,23 @@
/* @@package_name - v@@version - @@timestamp */
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// eslint-disable-next-line no-undef
const apiMetadata = require("../api-metadata.json");
if (typeof globalThis.browser === "undefined" || Object.getPrototypeOf(globalThis.browser) !== Object.prototype) {
const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received.";
const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)";
if (typeof browser === "undefined") {
// Wrapping the bulk of this polyfill in a one-time-use function is a minor
// optimization for Firefox. Since Spidermonkey does not fully parse the
// contents of a function until the first time it's called, and since it will
// never actually need to be called, this allows the polyfill to be included
// in Firefox nearly for free.
const wrapAPIs = () => {
const wrapAPIs = extensionAPIs => {
// NOTE: apiMetadata is associated to the content of the api-metadata.json file
// at build time by replacing the following "include" with the content of the
// JSON file.
const apiMetadata = {/* include("api-metadata.json") */};
if (Object.keys(apiMetadata).length === 0) {
throw new Error("api-metadata.json has not been included in browser-polyfill");
}
@ -74,22 +74,27 @@ if (typeof browser === "undefined") {
* promise.
* @param {function} promise.resolve
* The promise's resolution function.
* @param {function} promise.rejection
* @param {function} promise.reject
* The promise's rejection function.
* @param {object} metadata
* Metadata about the wrapped method which has created the callback.
* @param {integer} metadata.maxResolvedArgs
* The maximum number of arguments which may be passed to the
* callback created by the wrapped async function.
* @param {boolean} metadata.singleCallbackArg
* Whether or not the promise is resolved with only the first
* argument of the callback, alternatively an array of all the
* callback arguments is resolved. By default, if the callback
* function is invoked with only a single argument, that will be
* resolved to the promise, while all arguments will be resolved as
* an array if multiple are given.
*
* @returns {function}
* The generated callback function.
*/
const makeCallback = (promise, metadata) => {
return (...callbackArgs) => {
if (chrome.runtime.lastError) {
promise.reject(chrome.runtime.lastError);
} else if (metadata.singleCallbackArg || callbackArgs.length === 1) {
if (extensionAPIs.runtime.lastError) {
promise.reject(new Error(extensionAPIs.runtime.lastError.message));
} else if (metadata.singleCallbackArg ||
(callbackArgs.length <= 1 && metadata.singleCallbackArg !== false)) {
promise.resolve(callbackArgs[0]);
} else {
promise.resolve(callbackArgs);
@ -97,6 +102,8 @@ if (typeof browser === "undefined") {
};
};
const pluralizeArguments = (numArgs) => numArgs == 1 ? "argument" : "arguments";
/**
* Creates a wrapper function for a method with the given name and metadata.
*
@ -112,16 +119,18 @@ if (typeof browser === "undefined") {
* The maximum number of arguments which may be passed to the
* function. If called with more than this number of arguments, the
* wrapper will raise an exception.
* @param {integer} metadata.maxResolvedArgs
* The maximum number of arguments which may be passed to the
* callback created by the wrapped async function.
* @param {boolean} metadata.singleCallbackArg
* Whether or not the promise is resolved with only the first
* argument of the callback, alternatively an array of all the
* callback arguments is resolved. By default, if the callback
* function is invoked with only a single argument, that will be
* resolved to the promise, while all arguments will be resolved as
* an array if multiple are given.
*
* @returns {function(object, ...*)}
* The generated wrapper function.
*/
const wrapAsyncFunction = (name, metadata) => {
const pluralizeArguments = (numArgs) => numArgs == 1 ? "argument" : "arguments";
return function asyncFunctionWrapper(target, ...args) {
if (args.length < metadata.minArgs) {
throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
@ -132,7 +141,31 @@ if (typeof browser === "undefined") {
}
return new Promise((resolve, reject) => {
target[name](...args, makeCallback({resolve, reject}, metadata));
if (metadata.fallbackToNoCallback) {
// This API method has currently no callback on Chrome, but it return a promise on Firefox,
// and so the polyfill will try to call it with a callback first, and it will fallback
// to not passing the callback if the first call fails.
try {
target[name](...args, makeCallback({resolve, reject}, metadata));
} catch (cbError) {
console.warn(`${name} API method doesn't seem to support the callback parameter, ` +
"falling back to call it without a callback: ", cbError);
target[name](...args);
// Update the API method metadata, so that the next API calls will not try to
// use the unsupported callback anymore.
metadata.fallbackToNoCallback = false;
metadata.noCallback = true;
resolve();
}
} else if (metadata.noCallback) {
target[name](...args);
resolve();
} else {
target[name](...args, makeCallback({resolve, reject}, metadata));
}
});
};
};
@ -141,7 +174,7 @@ if (typeof browser === "undefined") {
* Wraps an existing method of the target object, so that calls to it are
* intercepted by the given wrapper function. The wrapper function receives,
* as its first argument, the original `target` object, followed by each of
* the arguments passed to the orginal method.
* the arguments passed to the original method.
*
* @param {object} target
* The original target object that the wrapped method belongs to.
@ -191,13 +224,12 @@ if (typeof browser === "undefined") {
*/
const wrapObject = (target, wrappers = {}, metadata = {}) => {
let cache = Object.create(null);
let handlers = {
has(target, prop) {
has(proxyTarget, prop) {
return prop in target || prop in cache;
},
get(target, prop, receiver) {
get(proxyTarget, prop, receiver) {
if (prop in cache) {
return cache[prop];
}
@ -232,6 +264,9 @@ if (typeof browser === "undefined") {
// of. Create a sub-object wrapper for it with the appropriate child
// metadata.
value = wrapObject(value, wrappers[prop], metadata[prop]);
} else if (hasOwnProperty(metadata, "*")) {
// Wrap all properties in * namespace.
value = wrapObject(value, wrappers[prop], metadata["*"]);
} else {
// We don't need to do any wrapping for this property,
// so just forward all access to the underlying object.
@ -253,7 +288,7 @@ if (typeof browser === "undefined") {
return value;
},
set(target, prop, value, receiver) {
set(proxyTarget, prop, value, receiver) {
if (prop in cache) {
cache[prop] = value;
} else {
@ -262,16 +297,27 @@ if (typeof browser === "undefined") {
return true;
},
defineProperty(target, prop, desc) {
defineProperty(proxyTarget, prop, desc) {
return Reflect.defineProperty(cache, prop, desc);
},
deleteProperty(target, prop) {
deleteProperty(proxyTarget, prop) {
return Reflect.deleteProperty(cache, prop);
},
};
return new Proxy(target, handlers);
// Per contract of the Proxy API, the "get" proxy handler must return the
// original value of the target if that value is declared read-only and
// non-configurable. For this reason, we create an object with the
// prototype set to `target` instead of using `target` directly.
// Otherwise we cannot return a custom object for APIs that
// are declared read-only and non-configurable, such as `chrome.devtools`.
//
// The proxy handlers themselves will still use the original `target`
// instead of the `proxyTarget`, so that the methods and properties are
// dereferenced via the original targets.
let proxyTarget = Object.create(target);
return new Proxy(proxyTarget, handlers);
};
/**
@ -304,6 +350,33 @@ if (typeof browser === "undefined") {
},
});
const onRequestFinishedWrappers = new DefaultWeakMap(listener => {
if (typeof listener !== "function") {
return listener;
}
/**
* Wraps an onRequestFinished listener function so that it will return a
* `getContent()` property which returns a `Promise` rather than using a
* callback API.
*
* @param {object} req
* The HAR entry object representing the network request.
*/
return function onRequestFinished(req) {
const wrappedReq = wrapObject(req, {} /* wrappers */, {
getContent: {
minArgs: 0,
maxArgs: 0,
},
});
listener(wrappedReq);
};
});
// Keep track if the deprecation warning has been logged at least once.
let loggedSendResponseDeprecationWarning = false;
const onMessageWrappers = new DefaultWeakMap(listener => {
if (typeof listener !== "function") {
return listener;
@ -327,38 +400,146 @@ if (typeof browser === "undefined") {
* yield a response. False otherwise.
*/
return function onMessage(message, sender, sendResponse) {
let result = listener(message, sender);
let didCallSendResponse = false;
if (isThenable(result)) {
result.then(sendResponse, error => {
console.error(error);
sendResponse(error);
});
let wrappedSendResponse;
let sendResponsePromise = new Promise(resolve => {
wrappedSendResponse = function(response) {
if (!loggedSendResponseDeprecationWarning) {
console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack);
loggedSendResponseDeprecationWarning = true;
}
didCallSendResponse = true;
resolve(response);
};
});
return true;
} else if (result !== undefined) {
sendResponse(result);
let result;
try {
result = listener(message, sender, wrappedSendResponse);
} catch (err) {
result = Promise.reject(err);
}
const isResultThenable = result !== true && isThenable(result);
// If the listener didn't returned true or a Promise, or called
// wrappedSendResponse synchronously, we can exit earlier
// because there will be no response sent from this listener.
if (result !== true && !isResultThenable && !didCallSendResponse) {
return false;
}
// A small helper to send the message if the promise resolves
// and an error if the promise rejects (a wrapped sendMessage has
// to translate the message into a resolved promise or a rejected
// promise).
const sendPromisedResult = (promise) => {
promise.then(msg => {
// send the message value.
sendResponse(msg);
}, error => {
// Send a JSON representation of the error if the rejected value
// is an instance of error, or the object itself otherwise.
let message;
if (error && (error instanceof Error ||
typeof error.message === "string")) {
message = error.message;
} else {
message = "An unexpected error occurred";
}
sendResponse({
__mozWebExtensionPolyfillReject__: true,
message,
});
}).catch(err => {
// Print an error on the console if unable to send the response.
console.error("Failed to send onMessage rejected reply", err);
});
};
// If the listener returned a Promise, send the resolved value as a
// result, otherwise wait the promise related to the wrappedSendResponse
// callback to resolve and send it as a response.
if (isResultThenable) {
sendPromisedResult(result);
} else {
sendPromisedResult(sendResponsePromise);
}
// Let Chrome know that the listener is replying.
return true;
};
});
const staticWrappers = {
runtime: {
onMessage: wrapEvent(onMessageWrappers),
},
const wrappedSendMessageCallback = ({reject, resolve}, reply) => {
if (extensionAPIs.runtime.lastError) {
// Detect when none of the listeners replied to the sendMessage call and resolve
// the promise to undefined as in Firefox.
// See https://github.com/mozilla/webextension-polyfill/issues/130
if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) {
resolve();
} else {
reject(new Error(extensionAPIs.runtime.lastError.message));
}
} else if (reply && reply.__mozWebExtensionPolyfillReject__) {
// Convert back the JSON representation of the error into
// an Error instance.
reject(new Error(reply.message));
} else {
resolve(reply);
}
};
// Create an object that has the real target as its prototype
// to prevent a Proxy violation exception for the devtools API getter
// (which is a read-only non-configurable property on the original target).
const targetObject = Object.create(chrome);
const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => {
if (args.length < metadata.minArgs) {
throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
}
return wrapObject(targetObject, staticWrappers, apiMetadata);
if (args.length > metadata.maxArgs) {
throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
}
return new Promise((resolve, reject) => {
const wrappedCb = wrappedSendMessageCallback.bind(null, {resolve, reject});
args.push(wrappedCb);
apiNamespaceObj.sendMessage(...args);
});
};
const staticWrappers = {
devtools: {
network: {
onRequestFinished: wrapEvent(onRequestFinishedWrappers),
},
},
runtime: {
onMessage: wrapEvent(onMessageWrappers),
onMessageExternal: wrapEvent(onMessageWrappers),
sendMessage: wrappedSendMessage.bind(null, "sendMessage", {minArgs: 1, maxArgs: 3}),
},
tabs: {
sendMessage: wrappedSendMessage.bind(null, "sendMessage", {minArgs: 2, maxArgs: 3}),
},
};
const settingMetadata = {
clear: {minArgs: 1, maxArgs: 1},
get: {minArgs: 1, maxArgs: 1},
set: {minArgs: 1, maxArgs: 1},
};
apiMetadata.privacy = {
network: {"*": settingMetadata},
services: {"*": settingMetadata},
websites: {"*": settingMetadata},
};
return wrapObject(extensionAPIs, staticWrappers, apiMetadata);
};
// The build process adds a UMD wrapper around this file, which makes the
// `module` variable available.
module.exports = wrapAPIs(); // eslint-disable-line no-undef
module.exports = wrapAPIs(chrome);
} else {
module.exports = browser; // eslint-disable-line no-undef
module.exports = globalThis.browser;
}

View File

@ -1,11 +1,9 @@
{
"env": {
"mocha": true,
"node": true,
"browser": true,
"webextensions": true
"mocha": true,
"webextensions": true,
},
"globals": {},
"rules": {
"max-nested-callbacks": ["warn", 6]
}

12
test/fixtures/browserify-tape.js vendored Normal file
View File

@ -0,0 +1,12 @@
const browserify = require("browserify");
const b = browserify();
b.add("./test/fixtures/tape-standalone.js");
b.transform("global-replaceify", {
global: true,
replacements: {
setImmediate: "require('timers').setImmediate",
},
});
b.bundle().pipe(process.stdout);

View File

@ -0,0 +1,20 @@
<!DOCTYPE>
<html>
<head>
<title>Test Extension Background page</title>
<meta charset="utf-8">
</head>
<body>
<!--
The following two DOM elements ensure that the polyfill doesn't detect the
globals defined for these DOM element ids as the Extensions API objects.
-->
<div id="browser"></div>
<div id="browser"></div>
<div id="chrome"></div>
<script src="copy-original-api-objects.js"></script>
<script src="browser-polyfill.js"></script>
<script src="background.js"></script>
</body>
</html>

View File

@ -0,0 +1,14 @@
/* global originalAPIObjects */
browser.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
if (msg !== "test-api-object-in-background-page") {
throw new Error(`Unexpected message received: ${msg}`);
}
return {
browserIsDefined: !!browser,
chromeIsDefined: !!chrome,
browserIsUnchanged: browser === originalAPIObjects.browser,
windowBrowserIsUnchanged: window.browser === originalAPIObjects.browser,
};
});

View File

@ -0,0 +1,54 @@
/* global originalAPIObjects */
test("browser api object in content script", (t) => {
t.ok(browser && browser.runtime, "a global browser API object should be defined");
t.ok(chrome && chrome.runtime, "a global chrome API object should be defined");
if (navigator.userAgent.includes("Firefox/")) {
// Check that the polyfill didn't create a polyfill wrapped browser API object on Firefox.
t.equal(browser, originalAPIObjects.browser, "browser API object should not be changed on Firefox");
// On Firefox, window is not the global object for content scripts, and so we expect window.browser to not
// be defined.
t.equal(window.browser, undefined, "window.browser is expected to be undefined on Firefox");
} else {
// Check that the polyfill has created a wrapped API namespace as expected.
t.notEqual(browser.runtime, chrome.runtime, "browser.runtime and chrome.runtime should not be equal");
// On chrome, window is the global object and so the polyfilled browser API should
// be also equal to window.browser.
t.equal(browser, window.browser, "browser and window.browser should be the same object");
}
});
test("browser api object in background page", async (t) => {
const reply = await browser.runtime.sendMessage("test-api-object-in-background-page");
t.ok(reply.browserIsDefined, "a global browser API object should be defined");
t.ok(reply.chromeIsDefined, "a global chrome API object should be defined");
if (navigator.userAgent.includes("Firefox/")) {
t.ok(reply.browserIsUnchanged, "browser API object should not be changed on Firefox");
t.ok(reply.windowBrowserIsUnchanged, "window.browser API object should not be changed on Firefox");
} else {
t.ok(!reply.browserIsUnchanged, "browser API object should have been defined by the polyfill");
t.ok(!reply.windowBrowserIsUnchanged, "window.browser API object should have been defined by the polyfill");
}
});
test("error types", async (t) => {
if (navigator.userAgent.includes("Firefox/")) {
try {
await browser.storage.sync.set({a: "a"});
t.fail("It should throw when attempting to call storage.sync with a temporary addon ID");
} catch (error) {
t.equal(error.message, "The storage API will not work with a temporary addon ID. Please add an explicit addon ID to your manifest. For more information see https://mzl.la/3lPk1aE.");
t.ok(error instanceof Error);
}
} else {
await new Promise(resolve => {
chrome.storage.local.set({a: "a".repeat(10000000)}, resolve);
});
t.ok(chrome.runtime.lastError, "It should throw when attempting to set an object over quota");
t.equal(chrome.runtime.lastError.message, "QUOTA_BYTES quota exceeded");
t.notOk(chrome.runtime.lastError instanceof Error);
}
});

View File

@ -0,0 +1,8 @@
// Store a copy of the references to the original API objects.
const originalAPIObjects = { // eslint-disable-line no-unused-vars
// NOTE: on the Browsers that do not provide the browser API object natively,
// this will initially point to the HTMLCollection of the <div id="browser"> elements
// that are part of the background page.
browser,
chrome,
};

View File

@ -0,0 +1,25 @@
{
"manifest_version": 2,
"name": "test-detect-browser-api-object-in-content-script",
"version": "0.1",
"description": "test-detect-browser-api-object-in-content-script",
"background": {
"page": "background.html"
},
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"copy-original-api-objects.js",
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": [
"storage"
]
}

View File

@ -0,0 +1,12 @@
let onDevToolsPageLoaded = new Promise(resolve => {
const listener = () => {
browser.runtime.onConnect.removeListener(listener);
resolve();
};
browser.runtime.onConnect.addListener(listener);
});
browser.runtime.onMessage.addListener(async msg => {
await onDevToolsPageLoaded;
return browser.runtime.sendMessage(msg);
});

View File

@ -0,0 +1,34 @@
test("devtools.inspectedWindow.eval resolved with an error result", {
timeout: 5000,
}, async (t) => {
const {evalResult} = await browser.runtime.sendMessage({
apiMethod: "devtools.inspectedWindow.eval",
params: ["throw new Error('fake error');"],
});
t.ok(Array.isArray(evalResult), "devtools.inspectedWindow.eval should resolve to an array");
t.equal(evalResult[0], navigator.userAgent.includes("Firefox/") ? undefined : null,
"the first element should be null (on chrome) or undefined (on firefox)");
t.ok(evalResult[1].isException, "the second element should represent an exception");
t.ok(evalResult[1].value && evalResult[1].value.includes("fake error"),
"the second element value property should include the expected error message");
});
test("devtools.inspectedWindow.eval resolved without an error result", {
timeout: 5000,
}, async (t) => {
const {evalResult} = await browser.runtime.sendMessage({
apiMethod: "devtools.inspectedWindow.eval",
params: ["[document.documentElement.localName]"],
});
t.ok(Array.isArray(evalResult), "devtools.inspectedWindow.eval should resolve to an array");
if (navigator.userAgent.includes("Firefox/")) {
t.deepEqual(evalResult, [["html"], undefined], "got the expected values in the array");
} else {
t.deepEqual(evalResult, [["html"]], "got the expected values in the array");
}
});

View File

@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<script src="browser-polyfill.js"></script>
<script src="devtools_page.js"></script>
</head>
</html>

View File

@ -0,0 +1,14 @@
console.log("devtools page loaded");
browser.runtime.onMessage.addListener(async msg => {
switch (msg.apiMethod) {
case "devtools.inspectedWindow.eval": {
const evalResult = await browser.devtools.inspectedWindow.eval(...msg.params);
return {evalResult};
}
}
throw new Error(`devtools_page received an unxpected message: ${msg}`);
});
browser.runtime.connect({name: "devtools_page"});

View File

@ -0,0 +1,27 @@
{
"manifest_version": 2,
"name": "test-extension-devtools-api",
"version": "0.1",
"description": "test-extension-devtools-api",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
],
"run_at": "document_end"
}
],
"permissions": [],
"background": {
"scripts": [
"browser-polyfill.js",
"background.js"
]
},
"devtools_page": "devtools_page.html"
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
</head>
<body>
<script type='module' src='browser-polyfill.js'></script>
<script type='module' src='background.js'></script>
</body>
</html>

View File

@ -0,0 +1,3 @@
browser.runtime.onMessage.addListener(async (msg, sender) => {
return {bgReceived: msg};
});

View File

@ -0,0 +1,5 @@
test("Test browser.runtime.onMessage on polyfill loaded as es6 module", async (t) => {
const msg = "send-message-to-background-page";
const res = await browser.runtime.sendMessage(msg);
t.deepEqual(res, {bgReceived: msg}, "Got the expected reply");
});

View File

@ -0,0 +1,22 @@
{
"manifest_version": 2,
"name": "test-import-as-es6-module",
"version": "0.1",
"description": "test-import-as-es6-module",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": [],
"background": {
"page": "background.html"
}
}

18
test/fixtures/index.html vendored Normal file
View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<title>Browser Polyfill Test Page</title>
<meta charset="utf-8">
</head>
<body>
<h1>Browser Polyfill Test Page</h1>
<!--
The following two DOM elements ensure that the polyfill doesn't detect the
globals defined for these DOM element ids as the Extensions API objects.
-->
<div id="browser"></div>
<div id="browser"></div>
<div id="chrome"></div>
</body>
</html>

View File

@ -0,0 +1,39 @@
console.log(name, "background page loaded");
async function testMessageHandler(msg, sender) {
console.log(name, "background received msg", {msg, sender});
// We only expect messages coming from a content script in this test.
if (!sender.tab || !msg.startsWith("test-multiple-onmessage-listeners:")) {
return {
success: false,
failureReason: `An unexpected message has been received: ${JSON.stringify({msg, sender})}`,
};
}
if (msg.endsWith(":resolve-to-undefined")) {
return undefined;
}
if (msg.endsWith(":resolve-to-null")) {
return null;
}
return {
success: false,
failureReason: `An unexpected message has been received: ${JSON.stringify({msg, sender})}`,
};
}
// Register the same message handler twice.
browser.runtime.onMessage.addListener(testMessageHandler);
browser.runtime.onMessage.addListener(testMessageHandler);
// Register an additional message handler that always reply after
// a small latency time.
browser.runtime.onMessage.addListener(async (msg, sender) => {
await new Promise(resolve => setTimeout(resolve, 100));
return "resolved-to-string-with-latency";
});
console.log(name, "background page ready to receive a content script message...");

View File

@ -0,0 +1,18 @@
test("Multiple runtime.onmessage listeners which resolve to undefined", async (t) => {
const res = await browser.runtime.sendMessage("test-multiple-onmessage-listeners:resolve-to-undefined");
if (navigator.userAgent.includes("Firefox/")) {
t.deepEqual(res, undefined, "Got an undefined value as expected");
} else {
// NOTE: When an onMessage listener sends `undefined` in a response,
// Chrome internally converts it to null and the receiver receives it
// as a null object.
t.deepEqual(res, null, "Got a null value as expected on Chrome");
}
});
test("Multiple runtime.onmessage listeners which resolve to null", async (t) => {
const res = await browser.runtime.sendMessage("test-multiple-onmessage-listeners:resolve-to-null");
t.deepEqual(res, null, "Got a null value as expected");
});

View File

@ -0,0 +1,25 @@
{
"manifest_version": 2,
"name": "test-multiple-onmessage-listeners",
"version": "0.1",
"description": "test-multiple-onmessage-listeners",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": [],
"background": {
"scripts": [
"browser-polyfill.js",
"background.js"
]
}
}

View File

@ -0,0 +1,5 @@
browser.runtime.onMessage.addListener(async (msg) => {
let {method, args} = msg;
let result = await browser.privacy.services.passwordSavingEnabled[method](...args);
return {result, type: typeof result};
});

View File

@ -0,0 +1,48 @@
test("privacy API should be unavailable in the content script", (t) => {
t.deepEqual(browser.privacy, undefined, "browser.privacy should not be available in a content script");
});
test("privacy API should support promises", async (t) => {
async function callSettingAPI(method, ...args) {
// Invokes: browser.privacy.services.passwordSavingEnabled[method](...args);
let {type, result} = await browser.runtime.sendMessage({method, args});
// In Chrome `undefined` values are serialized to `null`, so check the type
// as determined in the background page.
return type === "undefined" ? undefined : result;
}
let res = await callSettingAPI("get", {});
t.deepEqual(res, {
levelOfControl: "controllable_by_this_extension",
// Enabled by default in Chrome; disabled by default in Firefox.
value: !navigator.userAgent.includes("Firefox/"),
}, "passwordSavingEnabled.get() resolves to the initial value");
const defaultValue = res.value;
const newValue = !defaultValue;
res = await callSettingAPI("set", {value: newValue});
if (navigator.userAgent.includes("Firefox/")) {
t.equal(res, true, "passwordSavingEnabled.set() resolves to true");
} else {
t.equal(res, undefined, "passwordSavingEnabled.set() resolves to a void value");
}
res = await callSettingAPI("get", {});
t.deepEqual(res, {
levelOfControl: "controlled_by_this_extension",
value: newValue,
}, "passwordSavingEnabled.get() resolves to the updated value");
res = await callSettingAPI("clear", {});
if (navigator.userAgent.includes("Firefox/")) {
t.equal(res, true, "passwordSavingEnabled.clear() resolves to true");
} else {
t.equal(res, undefined, "passwordSavingEnabled.clear() resolves to a void value");
}
res = await callSettingAPI("get", {});
t.deepEqual(res, {
levelOfControl: "controllable_by_this_extension",
value: defaultValue,
}, "passwordSavingEnabled.get() resolves to the default value");
});

View File

@ -0,0 +1,25 @@
{
"manifest_version": 2,
"name": "test-privacy",
"version": "0.1",
"description": "test-privacy",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": ["privacy"],
"background": {
"scripts": [
"browser-polyfill.js",
"background.js"
]
}
}

View File

@ -0,0 +1,69 @@
const {name} = browser.runtime.getManifest();
console.log(name, "background page loaded");
browser.runtime.onMessage.addListener((msg, sender, sendResponse) => {
console.log(name, "background received msg", {msg, sender});
switch (msg) {
case "test - sendMessage with returned Promise reply":
try {
browser.pageAction.show(sender.tab.id);
} catch (err) {
return Promise.resolve(`Unexpected error on pageAction.show: ${err}`);
}
return Promise.resolve("bg page reply 1");
case "test - sendMessage with returned value reply":
// This is supposed to be ignored and the sender should receive
// a reply from the second listener.
return "Unexpected behavior: a plain return value should not be sent as a result";
case "test - sendMessage with synchronous sendResponse":
sendResponse("bg page reply 3");
return "value returned after calling sendResponse synchrously";
case "test - sendMessage with asynchronous sendResponse":
setTimeout(() => sendResponse("bg page reply 4"), 50);
return true;
case "test - second listener if the first does not reply":
// This is supposed to be ignored and the sender should receive
// a reply from the second listener.
return false;
case "test - sendMessage with returned rejected Promise with Error value":
return Promise.reject(new Error("rejected-error-value"));
case "test - sendMessage with returned rejected Promise with non-Error value":
return Promise.reject("rejected-non-error-value");
case "test - sendMessage with returned rejected Promise with non-Error value with message property":
return Promise.reject({message: "rejected-non-error-message"});
case "test - sendMessage with listener callback throws":
throw new Error("listener throws");
case "test - sendMessage and no listener answers":
return undefined;
default:
return Promise.resolve(
`Unxpected message received by the background page: ${JSON.stringify(msg)}\n`);
}
});
browser.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === "test - sendMessage and no listener answers") {
return undefined;
}
setTimeout(() => {
sendResponse("second listener reply");
}, 100);
return true;
});
console.log(name, "background page ready to receive a content script message...");

View File

@ -0,0 +1,82 @@
test("sendMessage with returned Promise reply", async (t) => {
const reply = await browser.runtime.sendMessage("test - sendMessage with returned Promise reply");
t.equal(reply, "bg page reply 1");
});
test("sendMessage with returned value reply", async (t) => {
const reply = await browser.runtime.sendMessage("test - sendMessage with returned value reply");
t.equal(reply, "second listener reply");
});
test("sendMessage with synchronous sendResponse", async (t) => {
const reply = await browser.runtime.sendMessage("test - sendMessage with synchronous sendResponse");
t.equal(reply, "bg page reply 3");
});
test("sendMessage with asynchronous sendResponse", async (t) => {
const reply = await browser.runtime.sendMessage("test - sendMessage with asynchronous sendResponse");
t.equal(reply, "bg page reply 4");
});
test("second listener if the first does not reply", async (t) => {
const reply = await browser.runtime.sendMessage("test - second listener if the first does not reply");
t.equal(reply, "second listener reply");
});
test("sendMessage with returned rejected Promise with Error value", async (t) => {
try {
const reply = await browser.runtime.sendMessage(
"test - sendMessage with returned rejected Promise with Error value");
t.fail(`Unexpected successfully reply while expecting a rejected promise`);
t.equal(reply, undefined, "Unexpected successfully reply");
} catch (err) {
t.ok(err instanceof Error, "Got an error object as expected");
t.equal(err.message, "rejected-error-value", "Got an error rejection with the expected message");
}
});
test("sendMessage with returned rejected Promise with non-Error value", async (t) => {
try {
const reply = await browser.runtime.sendMessage(
"test - sendMessage with returned rejected Promise with non-Error value");
t.fail(`Unexpected successfully reply while expecting a rejected promise`);
t.equal(reply, undefined, "Unexpected successfully reply");
} catch (err) {
// Unfortunately Firefox currently rejects an error with an "undefined"
// message in Firefox 60 and "An unexpected error occurred" in Firefox 59,
// in the meantime we just check that the object rejected is an instance
// of Error.
t.ok(err instanceof Error, "Got an error object as expected");
}
});
test("sendMessage with returned rejected Promise with non-Error value with message property", async (t) => {
try {
const reply = await browser.runtime.sendMessage(
"test - sendMessage with returned rejected Promise with non-Error value with message property");
t.fail(`Unexpected successfully reply while expecting a rejected promise`);
t.equal(reply, undefined, "Unexpected successfully reply");
} catch (err) {
// Firefox currently converts any rejection with a message property into an error instance
// with the value of that message property as the error message.
t.ok(err instanceof Error, "Got an error object as expected");
t.equal(err.message, "rejected-non-error-message", "Got an error rejection with the expected message");
}
});
test("sendMessage with listener callback throws", async (t) => {
try {
const reply = await browser.runtime.sendMessage(
"test - sendMessage with listener callback throws");
t.fail(`Unexpected successfully reply while expecting a rejected promise`);
t.equal(reply, undefined, "Unexpected successfully reply");
} catch (err) {
t.ok(err instanceof Error, "Got an error object as expected");
t.equal(err.message, "listener throws", "Got an error with the expected message");
}
});
test("sendMessage and no listener answers", async (t) => {
const reply = await browser.runtime.sendMessage("test - sendMessage and no listener answers");
t.equal(reply, undefined, "Got undefined reply as expected");
});

View File

@ -0,0 +1,28 @@
{
"manifest_version": 2,
"name": "test-extension-runtime-messaging",
"version": "0.1",
"description": "test-extension-runtime-messaging",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": [],
"background": {
"scripts": [
"browser-polyfill.js",
"background.js"
]
},
"page_action": {
"default_title": "a page action"
}
}

View File

@ -0,0 +1,36 @@
console.log(name, "background page loaded");
browser.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
console.log(name, "background received msg", {msg, sender});
// We only expect messages coming from a content script in this test.
if (!sender.tab || msg != "test-tabssendMessage-unknown-tabid") {
return {
success: false,
failureReason: `An unexpected message has been received: ${JSON.stringify({msg, sender})}`,
};
}
try {
const tabs = await browser.tabs.query({});
const lastValidTabId = tabs.reduce((acc, tab) => {
return Math.max(acc, tab.id);
}, 0);
const INVALID_TABID = lastValidTabId + 100;
await browser.tabs.sendMessage(INVALID_TABID, "message-to-unknown-tab");
return {
success: false,
failureReason: `browser.tabs.sendMessage should reject on sending messages to non-existing tab`,
};
} catch (err) {
return {
success: true,
isRejected: true,
errorMessage: err.message,
};
}
});
console.log(name, "background page ready to receive a content script message...");

View File

@ -0,0 +1,21 @@
test("tabs.sendMessage reject when sending to unknown tab id", async (t) => {
const res = await browser.runtime.sendMessage("test-tabssendMessage-unknown-tabid");
let errorMessage = "Could not establish connection. Receiving end does not exist.";
const firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || ["", "0"])[1];
if (firefoxVersion === 79) {
// Value of error message regressed in:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1583484
// and got fixed in Firefox 83 in:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1665568
errorMessage = "Error: tab is null";
} else if (firefoxVersion >= 80 && firefoxVersion < 83) {
// Raw error message leaked until it got sanitized again with
// https://bugzilla.mozilla.org/show_bug.cgi?id=1655624
errorMessage = "An unexpected error occurred";
}
t.deepEqual(res, {
success: true,
isRejected: true,
errorMessage,
}, "The background page got a rejection as expected");
});

View File

@ -0,0 +1,25 @@
{
"manifest_version": 2,
"name": "test-tabs-sendmessage",
"version": "0.1",
"description": "test-tabs-sendmessage",
"content_scripts": [
{
"matches": [
"http://localhost/*"
],
"js": [
"browser-polyfill.js",
"tape.js",
"content.js"
]
}
],
"permissions": [],
"background": {
"scripts": [
"browser-polyfill.js",
"background.js"
]
}
}

68
test/fixtures/tape-standalone.js vendored Normal file
View File

@ -0,0 +1,68 @@
const tape = require("tape-async");
const DEFAULT_TIMEOUT = 500;
let browser = "unknown";
if (navigator.userAgent.includes("Chrome/")) {
browser = "Chrome";
} else if (navigator.userAgent.includes("Firefox/")) {
browser = "Firefox";
}
// Export as a global a wrapped test function which enforces a timeout by default.
/**
* @param {string} desc
* The test description
* @param {object} [options]
* The test options, can be omitted.
* @param {number} [options.timeout=DEFAULT_TIMEOUT]
* The time after which the test fails automatically, unless it has already passed.
* @param {boolean} [options.skip]
* Whether the test case should be skipped.
* @param {function(tape.Test):(void|Promise<void>)} fn
* The test case function, takes the test object as a callback.
*/
window.test = (desc, options, fn) => {
if (typeof options === "function") {
// Allow swapping options with fn
[fn, options] = [options, fn];
}
options = {
timeout: DEFAULT_TIMEOUT,
...options,
};
tape(`${desc} (${browser})`, options, async (t) => {
await fn(t);
});
};
// Export the rest of the property usually available on the tape test object.
window.test.skip = tape.skip.bind(tape);
window.test.onFinish = tape.onFinish.bind(tape);
window.test.onFailure = tape.onFailure.bind(tape);
// Configure dump test results into an HTML pre element
// added to the test page.
const stream = tape.createStream();
let results = "";
stream.on("data", (result) => {
// Skip the TAP protocol version from the collected logs.
if (!result.startsWith("TAP version")) {
console.log("TAP test result:", result);
results += result;
}
});
stream.on("end", () => {
try {
const el = document.createElement("pre");
el.setAttribute("id", "test-results");
el.textContent = results;
document.body.appendChild(el);
} catch (err) {
console.error(err);
} finally {
console.log("TAP tests completed.");
}
});

245
test/integration/setup.js Normal file
View File

@ -0,0 +1,245 @@
"use strict";
const fs = require("fs");
const http = require("http");
const path = require("path");
const browserify = require("browserify");
const finalhandler = require("finalhandler");
const serveStatic = require("serve-static");
const {Builder, By, until} = require("selenium-webdriver");
const test = require("tape-async");
const tmp = require("tmp");
const {cp} = require("shelljs");
const TEST_TIMEOUT = 5000;
const launchBrowser = async (launchOptions) => {
const browser = launchOptions.browser;
const extensionPath = launchOptions.extensionPath;
const openDevTools = launchOptions.openDevTools;
let driver;
if (browser === "chrome") {
const chrome = require("selenium-webdriver/chrome");
const chromedriver = require("chromedriver");
if (process.env.HEADLESS === "1") {
console.warn("WARN: Chrome doesn't currently support extensions in headless mode. " +
"Falling back to non-headless mode");
}
const options = new chrome.Options();
options.addArguments([
`--load-extension=${extensionPath}`,
// See issue #85 for a rationale.
"--no-sandbox",
]);
if (openDevTools) {
options.addArguments(["-auto-open-devtools-for-tabs"]);
}
if (process.env.TEST_NATIVE_CRX_BINDINGS === "1") {
console.warn("NOTE: Running tests on a Chrome instance with NativeCrxBindings enabled.");
options.addArguments([
"--enable-features=NativeCrxBindings",
]);
}
const service = new chrome.ServiceBuilder(chromedriver.path);
if (process.env.CHROMEDRIVER_VERBOSE_LOGFILE) {
// Prevent intermittent failures due to limited resources while running
// in small VMs / docker containers (See #256 for a rationale).
const logsPath = process.env.CHROMEDRIVER_VERBOSE_LOGFILE;
console.warn(`NOTE: Verbose chromedriver logs: ${logsPath}`);
service.loggingTo(logsPath);
service.enableVerboseLogging();
}
driver = await new Builder()
.forBrowser("chrome")
.setChromeOptions(options)
.setChromeService(service)
.build();
} else if (browser === "firefox") {
const firefox = require("selenium-webdriver/firefox");
const geckodriver = require("geckodriver");
const {Command} = require("selenium-webdriver/lib/command");
const options = new firefox.Options();
if (process.env.HEADLESS === "1") {
options.headless();
}
if (openDevTools) {
options.addArguments("-devtools");
}
driver = await new Builder()
.forBrowser("firefox")
.setFirefoxOptions(options)
.setFirefoxService(new firefox.ServiceBuilder(geckodriver.path))
.build();
const command = new Command("install addon")
.setParameter("path", extensionPath)
.setParameter("temporary", true);
await driver.execute(command);
} else {
const errorHelpMsg = (
"Set a supported browser (firefox or chrome) " +
"using the TEST_BROWSER_TYPE environment var.");
throw new Error(`Target browser not supported yet: ${browser}. ${errorHelpMsg}`);
}
return driver;
};
const createHTTPServer = async (path) => {
const serve = serveStatic(path);
const server = http.createServer((req, res) => {
serve(req, res, finalhandler(req, res));
});
return new Promise((resolve, reject) => {
server.listen((err) => {
if (err) {
reject(err);
} else {
resolve(server);
}
});
});
};
async function runExtensionTest(t, server, driver, extensionDirName, browser) {
try {
const url = `http://localhost:${server.address().port}`;
const userAgent = await driver.executeScript(() => window.navigator.userAgent);
t.pass(`Connected to ${browser} browser: ${userAgent}"`);
await driver.get(url);
// Merge tap results from the connected browser.
const el = await driver.wait(until.elementLocated(By.id("test-results")), 10000);
const testResults = await el.getAttribute("textContent");
console.log(testResults);
} catch (err) {
t.fail(err);
}
}
const awaitStreamEnd = (stream) => {
return new Promise((resolve, reject) => {
stream.on("end", resolve);
stream.on("error", reject);
});
};
const bundleTapeStandalone = async (destDir) => {
const bundleFileName = path.join(destDir, "tape.js");
const b = browserify();
b.add(path.join(__dirname, "..", "fixtures", "tape-standalone.js"));
// Inject setImmediate (used internally by tape).
b.transform("global-replaceify", {
global: true,
replacements: {
setImmediate: "require('timers').setImmediate",
},
});
const stream = b.bundle();
const onceStreamEnd = awaitStreamEnd(stream);
const destFileStream = fs.createWriteStream(bundleFileName);
const onceWritten = new Promise(resolve => {
destFileStream.on("close", resolve);
});
stream.pipe(destFileStream);
await Promise.all([onceStreamEnd, onceWritten]);
};
test.onFailure(() => {
process.exit(1);
});
/**
* @param {object} parameters
* @param {string} parameters.description
* @param {string[]} parameters.extensions
* @param {boolean|string|string[]} [parameters.skip]
* @param {boolean} [parameters.openDevTools]
*/
const defineExtensionTests = ({description, extensions, skip, openDevTools}) => {
for (const extensionDirName of extensions) {
test(`${description} (test extension: ${extensionDirName})`, async (tt) => {
let timeout;
let driver;
let server;
let tempDir;
const browser = process.env.TEST_BROWSER_TYPE;
if (skip) {
if (skip === true) {
tt.skip("Test extension skipped");
return;
} else if (skip instanceof Array ? skip.includes(browser) : skip === browser) {
tt.skip("Test extension skipped on: " + browser);
return;
}
console.log(`Skip condition ignored: '${skip}' != '${browser}'`);
}
try {
const srcExtensionPath = path.resolve(
path.join(__dirname, "..", "fixtures", extensionDirName));
const srcPolyfill = path.join(__dirname, "..", "..", "dist", "browser-polyfill.js");
tempDir = tmp.dirSync({unsafeCleanup: true});
const extensionPath = path.join(tempDir.name, extensionDirName);
cp("-rf", srcExtensionPath, extensionPath);
cp("-f", srcPolyfill, extensionPath);
cp("-f", `${srcPolyfill}.map`, extensionPath);
await bundleTapeStandalone(extensionPath);
server = await createHTTPServer(path.join(__dirname, "..", "fixtures"));
driver = await launchBrowser({extensionPath, browser, openDevTools});
await Promise.race([
runExtensionTest(tt, server, driver, extensionDirName, browser),
new Promise((resolve, reject) => {
timeout = setTimeout(() => reject(new Error(`test timeout after ${TEST_TIMEOUT}`)), TEST_TIMEOUT);
}),
]);
} finally {
clearTimeout(timeout);
if (driver) {
await driver.quit();
driver = null;
}
if (server) {
server.close();
server = null;
}
if (tempDir) {
tempDir.removeCallback();
}
}
});
}
};
module.exports = {
launchBrowser,
createHTTPServer,
defineExtensionTests,
};

View File

@ -0,0 +1,39 @@
"use strict";
const {defineExtensionTests} = require("./setup");
defineExtensionTests({
description: "polyfill imported as an ES6 module",
extensions: ["import-as-es6-extension"],
});
defineExtensionTests({
description: "browser.runtime.onMessage/sendMessage",
extensions: ["runtime-messaging-extension"],
});
defineExtensionTests({
description: "browser.runtime.onMessage/sendMessage",
extensions: ["tabs-sendmessage-extension"],
});
defineExtensionTests({
description: "browser.runtime.onMessage/sendMessage",
extensions: ["multiple-onmessage-listeners-extension"],
});
defineExtensionTests({
description: "polyfill should detect an existing browser API object in content scripts and extension pages",
extensions: ["detect-existing-browser-api-object"],
});
defineExtensionTests({
description: "Instance of BrowserSetting API",
extensions: ["privacy-setting-extension"],
});
defineExtensionTests({
description: "browser.devtools",
extensions: ["devtools-extension"],
openDevTools: true,
});

7
test/mocha-babel.js Normal file
View File

@ -0,0 +1,7 @@
require("@babel/register")({
presets: [["@babel/env", {
targets: {
node: "current",
},
}]],
});

View File

@ -1,11 +0,0 @@
echo "\nTest webextension-polyfill bundled with webpack"
echo "==============================================="
webpack test/fixtures/bundle-entrypoint.js /tmp/webpack-bundle.js
TEST_BUNDLED_POLYFILL=/tmp/webpack-bundle.js npm run test
echo "\nTest webextension-polyfill bundled with browserify"
echo "=================================================="
browserify test/fixtures/bundle-entrypoint.js > /tmp/browserify-bundle.js
TEST_BUNDLED_POLYFILL=/tmp/browserify-bundle.js npm run test

View File

@ -21,6 +21,30 @@ if (process.env.TEST_MINIFIED_POLYFILL) {
BROWSER_POLYFILL_PATH = process.env.TEST_BUNDLED_POLYFILL;
}
function getInputSourceMap() {
// Enabled only on CI until we have fixed the mapping to the source file
// (by making sure that babel generates a sourcemap that does also take into
// account the api metadata being interpolated into the src script).
//
// TODO(https://github.com/mozilla/webextension-polyfill/issues/348):
// disabling the sourcemapped code coverage will not be necessary anymore
// once we fix the generated sourcemap to correctly map to src/browser-polyfill.js
if (process.env.COVERAGE_WITH_SOURCEMAP != "1") {
return undefined;
}
if (process.env.TEST_BUNDLED_POLYFILL) {
// Running the unit tests on the bundled files are meant to be used as smoke tests,
// we don't need to collect code coverage for it.
throw new Error("Unexpected code coverage enabled while testing bundled modules");
}
let sourceMapPath = process.env.TEST_MINIFIED_POLYFILL
? "./dist/browser-polyfill.js.min.map"
: "./dist/browser-polyfill.js.map";
let sourceMap = JSON.parse(fs.readFileSync(sourceMapPath, {encoding: "utf-8"}));
sourceMap.sources = ["../src/browser-polyfill.js"];
return sourceMap;
}
// Create the jsdom window used to run the tests
const testDOMWindow = jsdom("", {virtualConsole}).defaultView;
@ -37,16 +61,29 @@ function setupTestDOMWindow(chromeObject, browserObject = undefined) {
return new Promise((resolve, reject) => {
const window = testDOMWindow;
// Ensure that "chrome.runtime.id" is set, because the polyfill is only
// loaded in extension environments.
if (chromeObject) {
if (!chromeObject.runtime) {
chromeObject.runtime = {};
}
if (!chromeObject.runtime.id) {
chromeObject.runtime.id = "some-test-id-from-test-setup";
}
}
// Inject the fake chrome object used as a fixture for the particular
// browser-polyfill test scenario.
window.chrome = chromeObject;
// Set (or reset) the browser property.
if (browserObject) {
window.browser = browserObject;
// Make the fake browser object a `window.Object` instance, so that
// it passes the `Object.getPrototypeOf(browser) !== Object.prototype`
// check, otherwise it is going to be overridden by the polyfill (See #153).
window.browser = Object.assign(window.Object(), browserObject);
} else {
// TODO: change into `delete window.browser` once tmpvar/jsdom#1622 has been fixed.
window.browser = undefined;
delete window.browser;
}
const scriptEl = window.document.createElement("script");
@ -58,7 +95,11 @@ function setupTestDOMWindow(chromeObject, browserObject = undefined) {
compact: false, esModules: false, produceSourceMap: false,
});
const scriptContent = fs.readFileSync(BROWSER_POLYFILL_PATH, "utf-8");
scriptEl.textContent = inst.instrumentSync(scriptContent, BROWSER_POLYFILL_PATH);
scriptEl.textContent = inst.instrumentSync(
scriptContent,
BROWSER_POLYFILL_PATH,
getInputSourceMap()
);
} else {
scriptEl.src = BROWSER_POLYFILL_PATH;
}

View File

@ -1,6 +1,6 @@
"use strict";
const {deepEqual, equal, fail, ok, throws} = require("chai").assert;
const {deepEqual, equal, fail, ok, throws, instanceOf} = require("chai").assert;
const sinon = require("sinon");
const {setupTestDOMWindow} = require("./setup");
@ -12,6 +12,7 @@ describe("browser-polyfill", () => {
alarms: {clear: sinon.stub()},
runtime: {
lastError: null,
openOptionsPage: sinon.stub(),
requestUpdateCheck: sinon.stub(),
},
tabs: {
@ -31,10 +32,15 @@ describe("browser-polyfill", () => {
fakeChrome.runtime.requestUpdateCheck
.onFirstCall().callsArgWith(0, "res1", "res2");
// Test for no callback arguments.
fakeChrome.runtime.openOptionsPage
.onFirstCall().callsArg(0);
return Promise.all([
window.browser.alarms.clear("test1"),
window.browser.tabs.query({active: true}),
window.browser.runtime.requestUpdateCheck(),
window.browser.runtime.openOptionsPage(),
]);
}).then(results => {
equal(results[0], "res1", "Fake alarms.clear call resolved to a single value");
@ -42,13 +48,15 @@ describe("browser-polyfill", () => {
"Fake tabs.query resolved to an array of values");
deepEqual(results[2], ["res1", "res2"],
"Fake runtime.requestUpdateCheck resolved to an array of values");
equal(results[3], undefined, "Fake runtime.openOptionsPage resolved to a void value.");
});
});
it("rejects the returned promise if chrome.runtime.lastError is not null", () => {
const fakeChrome = {
runtime: {
lastError: new Error("fake lastError"),
lastError: {message: "fake lastError"},
},
tabs: {
query: sinon.stub(),
@ -62,8 +70,11 @@ describe("browser-polyfill", () => {
return window.browser.tabs.query({active: true}).then(
() => fail("Expected a rejected promise"),
(err) => equal(err, fakeChrome.runtime.lastError,
"Got the expected error in the rejected promise")
(err) => {
instanceOf(err, window.Error, "Expected the error to be an instance of Error");
equal(err.message, fakeChrome.runtime.lastError.message,
"Got the expected error in the rejected promise");
}
);
});
});
@ -141,5 +152,93 @@ describe("browser-polyfill", () => {
});
});
});
it("returns a Promise for wrapped API methods without a callback on Chrome", () => {
const FAKE_ERROR_MSG = "API Schema validation error";
const fakeChrome = {
runtime: {lastError: null},
pageAction: {
show: sinon.spy((tabId, cb) => {
if (cb) {
throw new Error("Chrome do not expect a callback");
}
if (tabId == null) {
throw new Error(FAKE_ERROR_MSG);
}
}),
hide: sinon.spy((tabId, cb) => {
if (cb) {
throw new Error("Chrome do not expect a callback");
}
if (tabId == null) {
throw new Error(FAKE_ERROR_MSG);
}
}),
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
const {browser, Promise} = window;
const pageActionShowPromise = browser.pageAction.show(1).catch(err => err);
const pageActionHidePromise = browser.pageAction.hide(undefined).catch(err => err);
ok(pageActionShowPromise instanceof Promise,
"browser.pageAction.show returned a promise instance");
ok(pageActionHidePromise instanceof Promise,
"browser.pageAction.hide returned a promise instance");
return Promise.all([
pageActionShowPromise, pageActionHidePromise,
]).then(([pageActionShowResolved, pageActionHideRejected]) => {
ok(fakeChrome.pageAction.show.calledTwice, "chrome.pageAction.show has been called twice");
equal(fakeChrome.pageAction.show.firstCall.args.length, 2,
"chrome.pageAction.show first call has received a callback parameter");
equal(fakeChrome.pageAction.show.secondCall.args.length, 1,
"chrome.pageAction.show second call has received a single parameter");
equal(pageActionShowResolved, undefined, "pageAction.show resolved successfully");
ok(fakeChrome.pageAction.hide.calledTwice, "chrome.pageAction.hide has been called twice");
equal(fakeChrome.pageAction.hide.firstCall.args.length, 2,
"chrome.pageAction.hide first call has received a callback parameter");
equal(fakeChrome.pageAction.hide.secondCall.args.length, 1,
"chrome.pageAction.hide second call has received a single parameter");
ok(pageActionHideRejected instanceof Error,
"browser.pageAction.hide rejected value is an Error instance");
equal(pageActionHideRejected.message, FAKE_ERROR_MSG,
"browser.pageAction.hide rejected error has the expected message");
}).then(() => {
// Call pageAction.show and hide again to ensure that only after a successfull
// API call the wrapper will always call the API method without the callback parameter.
fakeChrome.pageAction.show.resetHistory();
fakeChrome.pageAction.hide.resetHistory();
const secondPageActionShowPromise = browser.pageAction.show(1).catch(err => err);
const secondPageActionHidePromise = browser.pageAction.hide(undefined).catch(err => err);
return Promise.all([secondPageActionShowPromise, secondPageActionHidePromise]);
}).then(([pageActionShowResolved, pageActionHideRejected]) => {
ok(fakeChrome.pageAction.show.calledOnce, "chrome.pageAction.show has been called once");
equal(fakeChrome.pageAction.show.firstCall.args.length, 1,
"chrome.pageAction.show call has not received a callback parameter");
ok(fakeChrome.pageAction.hide.calledTwice, "chrome.pageAction.hide has been called twice");
equal(fakeChrome.pageAction.hide.firstCall.args.length, 2,
"chrome.pageAction.hide first call has received a callback parameter");
equal(fakeChrome.pageAction.hide.secondCall.args.length, 1,
"chrome.pageAction.hide second call has received a single parameter");
ok(pageActionHideRejected instanceof Error,
"browser.pageAction.hide rejected value is an Error instance");
equal(pageActionHideRejected.message, FAKE_ERROR_MSG,
"browser.pageAction.hide rejected error has the expected message");
});
});
});
});
});

View File

@ -5,6 +5,17 @@ const {deepEqual, equal, ok} = require("chai").assert;
const {setupTestDOMWindow} = require("./setup");
describe("browser-polyfill", () => {
it("throws an error in a non-extension environment", async () => {
try {
await setupTestDOMWindow(null);
ok(false, "The polyfill script should have failed to load.");
} catch (e) {
equal(e.message,
"This script should only be loaded in a browser extension.",
"Expected script to not load in a non-extension environment");
}
});
it("wraps the global chrome namespace with a global browser namespace", () => {
const fakeChrome = {};
return setupTestDOMWindow(fakeChrome).then(window => {

View File

@ -0,0 +1,119 @@
"use strict";
const {deepEqual, equal, ok} = require("chai").assert;
const sinon = require("sinon");
const {setupTestDOMWindow} = require("./setup");
describe("browser-polyfill", () => {
describe("wrapped devtools.network.onRequestFinished listener", () => {
it("does not wrap the listener if it is not a function", () => {
const fakeChrome = {
devtools: {
network: {
onRequestFinished: {
addListener: sinon.spy(),
},
},
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
const fakeNonFunctionListener = {fake: "non function listener"};
const browserOnRequestFinished = window.browser.devtools.network.onRequestFinished;
browserOnRequestFinished.addListener(fakeNonFunctionListener);
const fakeChromeOnRequestFinished = fakeChrome.devtools.network.onRequestFinished;
deepEqual(
fakeChromeOnRequestFinished.addListener.firstCall.args[0],
fakeNonFunctionListener,
"The non-function listener has not been wrapped"
);
});
});
it("promisifies the result", () => {
const fakeChrome = {
devtools: {
network: {
onRequestFinished: {
addListener: sinon.spy(),
hasListener: sinon.stub(),
removeListener: sinon.spy(),
},
},
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
const listener = sinon.spy();
const browserOnRequestFinished = window.browser.devtools.network.onRequestFinished;
browserOnRequestFinished.addListener(listener);
const fakeChromeOnRequestFinished = fakeChrome.devtools.network.onRequestFinished;
ok(fakeChromeOnRequestFinished.addListener.calledOnce,
"devtools.network.onRequestFinished.addListener has been called once");
const wrappedListener = fakeChromeOnRequestFinished.addListener.firstCall.args[0];
wrappedListener({
getContent(cb) {
cb("<html>...</html>", "text/html; charset=utf8");
},
});
ok(listener.calledOnce, "listener has been called once");
const req = listener.firstCall.args[0];
return req.getContent().then(([content, encodingOrMimeType]) => {
equal(content, "<html>...</html>");
// On Chrome this is the encoding ('' or 'base64') while on Firefox
// this is the MIME type of the resource.
// See: https://github.com/mozilla/webextension-polyfill/issues/249#issuecomment-740000461
equal(encodingOrMimeType, "text/html; charset=utf8");
});
});
});
it("promisifies the result with a wrapped Request object", () => {
const fakeChrome = {
devtools: {
network: {
onRequestFinished: {
addListener: sinon.spy(),
hasListener: sinon.stub(),
removeListener: sinon.spy(),
},
},
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
const listener = sinon.spy();
const browserOnRequestFinished = window.browser.devtools.network.onRequestFinished;
browserOnRequestFinished.addListener(listener);
const fakeChromeOnRequestFinished = fakeChrome.devtools.network.onRequestFinished;
ok(fakeChromeOnRequestFinished.addListener.calledOnce,
"devtools.network.onRequestFinished.addListener has been called once");
const request = Object.create({
inheritedProp: true,
getContent(cb) {
cb("", "");
},
});
const wrappedListener = fakeChromeOnRequestFinished.addListener.firstCall.args[0];
wrappedListener(request);
ok(listener.calledOnce, "listener has been called once");
const req = listener.firstCall.args[0];
ok(req.inheritedProp, "Wrapped request inherited prototype properties");
});
});
});
});

View File

@ -8,8 +8,10 @@ const {setupTestDOMWindow} = require("./setup");
describe("browser-polyfill", () => {
describe("proxies non-configurable read-only properties", () => {
it("creates a proxy that doesn't raise a Proxy violation exception", () => {
const fakeChrome = {};
const fakeChrome = {"devtools": {}};
// Override the property to make it non-configurable (needed to be sure that
// the polyfill is correctly workarounding the Proxy TypeError).
Object.defineProperty(fakeChrome, "devtools", {
enumarable: true,
configurable: false,
@ -22,8 +24,6 @@ describe("browser-polyfill", () => {
});
return setupTestDOMWindow(fakeChrome).then(window => {
window.browser.devtools; // eslint-disable-line
ok(window.browser.devtools.inspectedWindow,
"The non-configurable read-only property can be accessed");
@ -136,4 +136,81 @@ describe("browser-polyfill", () => {
});
});
});
describe("without side effects", () => {
it("should proxy non-wrapped methods", () => {
let lazyInitCount = 0;
const fakeChrome = {
get runtime() {
// Chrome lazily initializes API objects by replacing the getter with
// the value. The initialization is only allowed to occur once,
// after that `undefined` is returned and a warning is printed.
// https://chromium.googlesource.com/chromium/src/+/4d6b3a067994ce6dcf0ed9a9efd566c083736952/extensions/renderer/module_system.cc#414
//
// The polyfill should invoke the getter only once (on the global chrome object).
++lazyInitCount;
const onMessage = {
addListener(listener) {
equal(this, onMessage, "onMessage.addListener should be called on the original chrome.onMessage object");
},
};
const value = {onMessage};
Object.defineProperty(this, "runtime", {value});
return value;
},
get tabs() {
ok(false, "chrome.tabs should not lazily be initialized without explicit API call");
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
// This used to be equal(lazyInitCount, 0, ...), but was changed to
// accomodate a change in the implementation of the polyfill.
// To verify that APIs are not unnecessarily initialized, the fakeChrome
// object has a "tabs" getter that fails the test upon access.
equal(lazyInitCount, 1, "chrome.runtime should be initialized because chrome.runtime.id is accessed during polyfill initialization");
window.browser.runtime.onMessage.addListener(() => {});
equal(lazyInitCount, 1, "chrome.runtime should be initialized upon accessing browser.runtime");
window.browser.runtime.onMessage.addListener(() => {});
equal(lazyInitCount, 1, "chrome.runtime should be re-used upon accessing browser.runtime");
window.chrome.runtime.onMessage.addListener(() => {});
equal(lazyInitCount, 1, "chrome.runtime should be re-used upon accessing chrome.runtime");
});
});
});
describe("Privacy API", () => {
it("Should wrap chrome.privacy.* API", () => {
let lazyInitCount = 0;
const fakeChrome = {
privacy: {
get network() {
++lazyInitCount;
const networkPredictionEnabled = {
get: () => {},
set: () => {},
clear: () => {},
};
return {networkPredictionEnabled};
},
},
};
return setupTestDOMWindow(fakeChrome).then(window => {
equal(lazyInitCount, 0, "chrome.privacy.network is not accessed first");
const {get, set, clear} = window.browser.privacy.network.networkPredictionEnabled;
equal(get({}).then !== undefined, true, "Privacy API get method is a Promise");
equal(set({}).then !== undefined, true, "Privacy API set method is a Promise");
equal(clear({}).then !== undefined, true, "Privacy API clear method is a Promise");
equal(lazyInitCount, 1, "chrome.privacy.network should be accessed only once");
window.browser.privacy.network.networkPredictionEnabled.get({});
equal(lazyInitCount, 1, "chrome.privacy.network should be accessed only once");
});
});
});
});

View File

@ -117,8 +117,10 @@ describe("browser-polyfill", () => {
equal(secondMessageListener.firstCall.args[0], "call second wrapper");
});
});
});
it("sends the returned value as a message response", () => {
describe("sendResponse callback", () => {
it("ignores the sendResponse calls when the listener returns a promise", () => {
const fakeChrome = {
runtime: {
lastError: null,
@ -128,70 +130,136 @@ describe("browser-polyfill", () => {
},
};
// Plain value returned.
const messageListener = sinon.stub();
const firstResponse = "fake reply";
// Resolved Promise returned.
const secondResponse = Promise.resolve("fake reply 2");
// Rejected Promise returned.
const thirdResponse = Promise.reject("fake error 3");
return setupTestDOMWindow(fakeChrome).then(window => {
const listener = sinon.spy((msg, sender, sendResponse) => {
sendResponse("Ignored sendReponse callback on returned Promise");
const sendResponseSpy = sinon.spy();
return Promise.resolve("listener resolved value");
});
messageListener
.onFirstCall().returns(firstResponse)
.onSecondCall().returns(secondResponse)
.onThirdCall().returns(thirdResponse);
const sendResponseSpy = sinon.spy();
let wrappedListener;
window.browser.runtime.onMessage.addListener(listener);
ok(fakeChrome.runtime.onMessage.addListener.calledOnce,
"runtime.onMessage.addListener should have been called once");
let wrappedListener = fakeChrome.runtime.onMessage.addListener.firstCall.args[0];
let returnedValue = wrappedListener("test message", {name: "fake sender"}, sendResponseSpy);
equal(returnedValue, true, "the wrapped listener should have returned true");
ok(listener.calledOnce, "listener has been called once");
// Wait a promise to be resolved and then check the wrapped listener behaviors.
return Promise.resolve().then(() => {
ok(sendResponseSpy.calledOnce, "sendResponse callback called once");
equal(sendResponseSpy.firstCall.args[0], "listener resolved value",
"sendResponse has been called with the expected value");
});
});
});
it("ignores asynchronous sendResponse calls if the listener does not return true", () => {
const fakeChrome = {
runtime: {
lastError: null,
onMessage: {
addListener: sinon.spy(),
},
},
};
const waitPromises = [];
return setupTestDOMWindow(fakeChrome).then(window => {
window.browser.runtime.onMessage.addListener(messageListener);
const listenerReturnsFalse = sinon.spy((msg, sender, sendResponse) => {
waitPromises.push(Promise.resolve().then(() => {
sendResponse("Ignored sendReponse callback on returned false");
}));
ok(fakeChrome.runtime.onMessage.addListener.calledOnce);
return false;
});
wrappedListener = fakeChrome.runtime.onMessage.addListener.firstCall.args[0];
const listenerReturnsValue = sinon.spy((msg, sender, sendResponse) => {
waitPromises.push(Promise.resolve().then(() => {
sendResponse("Ignored sendReponse callback on non boolean/thenable return values");
}));
wrappedListener("fake message", {name: "fake sender"}, sendResponseSpy);
// Any return value that is not a promise should not be sent as a response,
// and any return value that is not true should make the sendResponse
// calls to be ignored.
return "Ignored return value";
});
ok(messageListener.calledOnce, "The unwrapped message listener has been called");
deepEqual(messageListener.firstCall.args,
["fake message", {name: "fake sender"}],
"The unwrapped message listener has received the expected parameters");
const listenerReturnsTrue = sinon.spy((msg, sender, sendResponse) => {
waitPromises.push(Promise.resolve().then(() => {
sendResponse("expected sendResponse value");
}));
ok(sendResponseSpy.calledOnce, "The sendResponse function has been called");
equal(sendResponseSpy.firstCall.args[0], "fake reply",
"sendResponse callback has been called with the expected parameters");
// Expect the asynchronous sendResponse call to be used to send a response
// when the listener returns true.
return true;
});
wrappedListener("fake message2", {name: "fake sender2"}, sendResponseSpy);
const sendResponseSpy = sinon.spy();
// Wait the second response promise to be resolved.
return secondResponse;
}).then(() => {
ok(messageListener.calledTwice,
"The unwrapped message listener has been called");
deepEqual(messageListener.secondCall.args,
["fake message2", {name: "fake sender2"}],
"The unwrapped listener has received the expected parameters");
window.browser.runtime.onMessage.addListener(listenerReturnsFalse);
window.browser.runtime.onMessage.addListener(listenerReturnsValue);
window.browser.runtime.onMessage.addListener(listenerReturnsTrue);
ok(sendResponseSpy.calledTwice, "The sendResponse function has been called");
equal(sendResponseSpy.secondCall.args[0], "fake reply 2",
"sendResponse callback has been called with the expected parameters");
}).then(() => {
wrappedListener("fake message3", {name: "fake sender3"}, sendResponseSpy);
equal(fakeChrome.runtime.onMessage.addListener.callCount, 3,
"runtime.onMessage.addListener should have been called 3 times");
// Wait the third response promise to be rejected.
return thirdResponse.catch(err => {
equal(messageListener.callCount, 3,
"The unwrapped message listener has been called");
deepEqual(messageListener.thirdCall.args,
["fake message3", {name: "fake sender3"}],
"The unwrapped listener has received the expected parameters");
let wrappedListenerReturnsFalse = fakeChrome.runtime.onMessage.addListener.firstCall.args[0];
let wrappedListenerReturnsValue = fakeChrome.runtime.onMessage.addListener.secondCall.args[0];
let wrappedListenerReturnsTrue = fakeChrome.runtime.onMessage.addListener.thirdCall.args[0];
equal(sendResponseSpy.callCount, 3,
"The sendResponse function has been called");
equal(sendResponseSpy.thirdCall.args[0], err,
"sendResponse callback has been called with the expected parameters");
let returnedValue = wrappedListenerReturnsFalse("test message", {name: "fake sender"}, sendResponseSpy);
equal(returnedValue, false, "the first wrapped listener should return false");
returnedValue = wrappedListenerReturnsValue("test message2", {name: "fake sender"}, sendResponseSpy);
equal(returnedValue, false, "the second wrapped listener should return false");
returnedValue = wrappedListenerReturnsTrue("test message3", {name: "fake sender"}, sendResponseSpy);
equal(returnedValue, true, "the third wrapped listener should return true");
ok(listenerReturnsFalse.calledOnce, "first listener has been called once");
ok(listenerReturnsValue.calledOnce, "second listener has been called once");
ok(listenerReturnsTrue.calledOnce, "third listener has been called once");
// Wait all the collected promises to be resolved and then check the wrapped listener behaviors.
return Promise.all(waitPromises).then(() => {
ok(sendResponseSpy.calledOnce, "sendResponse callback should have been called once");
equal(sendResponseSpy.firstCall.args[0], "expected sendResponse value",
"sendResponse has been called with the expected value");
});
});
});
it("resolves to undefined when no listeners reply", () => {
const fakeChrome = {
runtime: {
// This error message is defined as CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE
// in the polyfill sources and it is used to recognize when Chrome has detected that
// none of the listeners replied.
lastError: {
message: "The message port closed before a response was received.",
},
sendMessage: sinon.stub(),
},
};
fakeChrome.runtime.sendMessage.onFirstCall().callsArgWith(1, [undefined]);
return setupTestDOMWindow(fakeChrome).then(window => {
const promise = window.browser.runtime.sendMessage("some_message");
ok(fakeChrome.runtime.sendMessage.calledOnce, "sendMessage has been called once");
return promise.then(reply => {
deepEqual(reply, undefined, "sendMessage promise should be resolved to undefined");
});
});
});

240
types/index.d.ts vendored Executable file
View File

@ -0,0 +1,240 @@
// Type definitions for webextension-polyfill 0.8
// Project: https://github.com/mozilla/webextension-polyfill
// Definitions by: Santo Pfingsten <https://github.com/Lusito>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Generated using https://github.com/Lusito/webextension-polyfill-ts
// Generated from Mozilla sources. Do not manually edit!
import { ActivityLog as ImportedActivityLog } from "./namespaces/activityLog";
import { Alarms as ImportedAlarms } from "./namespaces/alarms";
import { Bookmarks as ImportedBookmarks } from "./namespaces/bookmarks";
import { Action as ImportedAction } from "./namespaces/action";
import { BrowserAction as ImportedBrowserAction } from "./namespaces/browserAction";
import { BrowserSettings as ImportedBrowserSettings } from "./namespaces/browserSettings";
import { BrowsingData as ImportedBrowsingData } from "./namespaces/browsingData";
import { CaptivePortal as ImportedCaptivePortal } from "./namespaces/captivePortal";
import { Clipboard as ImportedClipboard } from "./namespaces/clipboard";
import { Commands as ImportedCommands } from "./namespaces/commands";
import { ContentScripts as ImportedContentScripts } from "./namespaces/contentScripts";
import { ContextualIdentities as ImportedContextualIdentities } from "./namespaces/contextualIdentities";
import { Cookies as ImportedCookies } from "./namespaces/cookies";
import { DeclarativeContent as ImportedDeclarativeContent } from "./namespaces/declarativeContent";
import { Devtools as ImportedDevtools } from "./namespaces/devtools";
import { Dns as ImportedDns } from "./namespaces/dns";
import { Downloads as ImportedDownloads } from "./namespaces/downloads";
import { Events as ImportedEvents } from "./namespaces/events";
import { Experiments as ImportedExperiments } from "./namespaces/experiments";
import { Extension as ImportedExtension } from "./namespaces/extension";
import { ExtensionTypes as ImportedExtensionTypes } from "./namespaces/extensionTypes";
import { Find as ImportedFind } from "./namespaces/find";
import { GeckoProfiler as ImportedGeckoProfiler } from "./namespaces/geckoProfiler";
import { History as ImportedHistory } from "./namespaces/history";
import { I18n as ImportedI18n } from "./namespaces/i18n";
import { Identity as ImportedIdentity } from "./namespaces/identity";
import { Idle as ImportedIdle } from "./namespaces/idle";
import { Management as ImportedManagement } from "./namespaces/management";
import { Manifest as ImportedManifest } from "./namespaces/manifest";
import { ContextMenus as ImportedContextMenus } from "./namespaces/contextMenus";
import { Menus as ImportedMenus } from "./namespaces/menus";
import { NetworkStatus as ImportedNetworkStatus } from "./namespaces/networkStatus";
import { NormandyAddonStudy as ImportedNormandyAddonStudy } from "./namespaces/normandyAddonStudy";
import { Notifications as ImportedNotifications } from "./namespaces/notifications";
import { Omnibox as ImportedOmnibox } from "./namespaces/omnibox";
import { PageAction as ImportedPageAction } from "./namespaces/pageAction";
import { Permissions as ImportedPermissions } from "./namespaces/permissions";
import { Pkcs11 as ImportedPkcs11 } from "./namespaces/pkcs11";
import { Privacy as ImportedPrivacy } from "./namespaces/privacy";
import { Proxy as ImportedProxy } from "./namespaces/proxy";
import { Runtime as ImportedRuntime } from "./namespaces/runtime";
import { Scripting as ImportedScripting } from "./namespaces/scripting";
import { Search as ImportedSearch } from "./namespaces/search";
import { Sessions as ImportedSessions } from "./namespaces/sessions";
import { SidebarAction as ImportedSidebarAction } from "./namespaces/sidebarAction";
import { Storage as ImportedStorage } from "./namespaces/storage";
import { Tabs as ImportedTabs } from "./namespaces/tabs";
import { Theme as ImportedTheme } from "./namespaces/theme";
import { TopSites as ImportedTopSites } from "./namespaces/topSites";
import { Types as ImportedTypes } from "./namespaces/types";
import { Urlbar as ImportedUrlbar } from "./namespaces/urlbar";
import { UserScripts as ImportedUserScripts } from "./namespaces/userScripts";
import { WebNavigation as ImportedWebNavigation } from "./namespaces/webNavigation";
import { WebRequest as ImportedWebRequest } from "./namespaces/webRequest";
import { Windows as ImportedWindows } from "./namespaces/windows";
declare namespace Browser {
const activityLog: ActivityLog.Static;
const alarms: Alarms.Static;
const bookmarks: Bookmarks.Static;
const action: Action.Static;
const browserAction: BrowserAction.Static;
const browserSettings: BrowserSettings.Static;
const browsingData: BrowsingData.Static;
const captivePortal: CaptivePortal.Static;
const clipboard: Clipboard.Static;
const commands: Commands.Static;
const contentScripts: ContentScripts.Static;
const contextualIdentities: ContextualIdentities.Static;
const cookies: Cookies.Static;
const declarativeContent: DeclarativeContent.Static;
const devtools: Devtools.Static;
const dns: Dns.Static;
const downloads: Downloads.Static;
const events: Events.Static;
const experiments: Experiments.Static;
const extension: Extension.Static;
const extensionTypes: ExtensionTypes.Static;
const find: Find.Static;
const geckoProfiler: GeckoProfiler.Static;
const history: History.Static;
const i18n: I18n.Static;
const identity: Identity.Static;
const idle: Idle.Static;
const management: Management.Static;
const manifest: Manifest.Static;
const contextMenus: ContextMenus.Static;
const menus: Menus.Static;
const networkStatus: NetworkStatus.Static;
const normandyAddonStudy: NormandyAddonStudy.Static;
const notifications: Notifications.Static;
const omnibox: Omnibox.Static;
const pageAction: PageAction.Static;
const permissions: Permissions.Static;
const pkcs11: Pkcs11.Static;
const privacy: Privacy.Static;
const proxy: Proxy.Static;
const runtime: Runtime.Static;
const scripting: Scripting.Static;
const search: Search.Static;
const sessions: Sessions.Static;
const sidebarAction: SidebarAction.Static;
const storage: Storage.Static;
const tabs: Tabs.Static;
const theme: Theme.Static;
const topSites: TopSites.Static;
const types: Types.Static;
const urlbar: Urlbar.Static;
const userScripts: UserScripts.Static;
const webNavigation: WebNavigation.Static;
const webRequest: WebRequest.Static;
const windows: Windows.Static;
interface Browser {
activityLog: ActivityLog.Static;
alarms: Alarms.Static;
bookmarks: Bookmarks.Static;
action: Action.Static;
browserAction: BrowserAction.Static;
browserSettings: BrowserSettings.Static;
browsingData: BrowsingData.Static;
captivePortal: CaptivePortal.Static;
clipboard: Clipboard.Static;
commands: Commands.Static;
contentScripts: ContentScripts.Static;
contextualIdentities: ContextualIdentities.Static;
cookies: Cookies.Static;
declarativeContent: DeclarativeContent.Static;
devtools: Devtools.Static;
dns: Dns.Static;
downloads: Downloads.Static;
events: Events.Static;
experiments: Experiments.Static;
extension: Extension.Static;
extensionTypes: ExtensionTypes.Static;
find: Find.Static;
geckoProfiler: GeckoProfiler.Static;
history: History.Static;
i18n: I18n.Static;
identity: Identity.Static;
idle: Idle.Static;
management: Management.Static;
manifest: Manifest.Static;
contextMenus: ContextMenus.Static;
menus: Menus.Static;
networkStatus: NetworkStatus.Static;
normandyAddonStudy: NormandyAddonStudy.Static;
notifications: Notifications.Static;
omnibox: Omnibox.Static;
pageAction: PageAction.Static;
permissions: Permissions.Static;
pkcs11: Pkcs11.Static;
privacy: Privacy.Static;
proxy: Proxy.Static;
runtime: Runtime.Static;
scripting: Scripting.Static;
search: Search.Static;
sessions: Sessions.Static;
sidebarAction: SidebarAction.Static;
storage: Storage.Static;
tabs: Tabs.Static;
theme: Theme.Static;
topSites: TopSites.Static;
types: Types.Static;
urlbar: Urlbar.Static;
userScripts: UserScripts.Static;
webNavigation: WebNavigation.Static;
webRequest: WebRequest.Static;
windows: Windows.Static;
}
/* tslint:disable:strict-export-declare-modifiers */
export import ActivityLog = ImportedActivityLog;
export import Alarms = ImportedAlarms;
export import Bookmarks = ImportedBookmarks;
export import Action = ImportedAction;
export import BrowserAction = ImportedBrowserAction;
export import BrowserSettings = ImportedBrowserSettings;
export import BrowsingData = ImportedBrowsingData;
export import CaptivePortal = ImportedCaptivePortal;
export import Clipboard = ImportedClipboard;
export import Commands = ImportedCommands;
export import ContentScripts = ImportedContentScripts;
export import ContextualIdentities = ImportedContextualIdentities;
export import Cookies = ImportedCookies;
export import DeclarativeContent = ImportedDeclarativeContent;
export import Devtools = ImportedDevtools;
export import Dns = ImportedDns;
export import Downloads = ImportedDownloads;
export import Events = ImportedEvents;
export import Experiments = ImportedExperiments;
export import Extension = ImportedExtension;
export import ExtensionTypes = ImportedExtensionTypes;
export import Find = ImportedFind;
export import GeckoProfiler = ImportedGeckoProfiler;
export import History = ImportedHistory;
export import I18n = ImportedI18n;
export import Identity = ImportedIdentity;
export import Idle = ImportedIdle;
export import Management = ImportedManagement;
export import Manifest = ImportedManifest;
export import ContextMenus = ImportedContextMenus;
export import Menus = ImportedMenus;
export import NetworkStatus = ImportedNetworkStatus;
export import NormandyAddonStudy = ImportedNormandyAddonStudy;
export import Notifications = ImportedNotifications;
export import Omnibox = ImportedOmnibox;
export import PageAction = ImportedPageAction;
export import Permissions = ImportedPermissions;
export import Pkcs11 = ImportedPkcs11;
export import Privacy = ImportedPrivacy;
export import Proxy = ImportedProxy;
export import Runtime = ImportedRuntime;
export import Scripting = ImportedScripting;
export import Search = ImportedSearch;
export import Sessions = ImportedSessions;
export import SidebarAction = ImportedSidebarAction;
export import Storage = ImportedStorage;
export import Tabs = ImportedTabs;
export import Theme = ImportedTheme;
export import TopSites = ImportedTopSites;
export import Types = ImportedTypes;
export import Urlbar = ImportedUrlbar;
export import UserScripts = ImportedUserScripts;
export import WebNavigation = ImportedWebNavigation;
export import WebRequest = ImportedWebRequest;
export import Windows = ImportedWindows;
/* tslint:enable:strict-export-declare-modifiers */
}
// tslint:disable-next-line:export-just-namespace
export = Browser;

240
types/namespaces/action.d.ts vendored Executable file
View File

@ -0,0 +1,240 @@
/**
* Namespace: browser.action
* Generated from Mozilla sources. Do not manually edit!
*
* Use browser actions to put icons in the main browser toolbar, to the right of the address bar. In addition to its icon,
* a browser action can also have a tooltip, a badge, and a popup.
* Permissions: "manifest:action", "manifest:browser_action"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Tabs } from "./tabs";
import { Events } from "./events";
export namespace Action {
/**
* Specifies to which tab or window the value should be set, or from which one it should be retrieved.
* If no tab nor window is specified, the global value is set or retrieved.
*/
interface Details {
/**
* When setting a value, it will be specific to the specified tab, and will automatically reset when the tab navigates.
* When getting, specifies the tab to get the value from; if there is no tab-specific value,
* the window one will be inherited.
* Optional.
*/
tabId?: number;
/**
* When setting a value, it will be specific to the specified window. When getting, specifies the window to get the value
* from; if there is no window-specific value, the global one will be inherited.
* Optional.
*/
windowId?: number;
}
type ColorArray = [number, number, number, number];
/**
* Pixel data for an image. Must be an ImageData object (for example, from a <code>canvas</code> element).
*/
interface ImageDataType extends ImageData {
[s: string]: unknown;
}
/**
* An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example,
* opaque red is <code>[255, 0, 0, 255]</code>. Can also be a string with a CSS value, with opaque red being <code>
* #FF0000</code> or <code>#F00</code>.
*/
type ColorValue = string | ColorArray | null;
/**
* Information sent when a browser action is clicked.
*/
interface OnClickData {
/**
* An array of keyboard modifiers that were held while the menu item was clicked.
*/
modifiers: OnClickDataModifiersItemEnum[];
/**
* An integer value of button by which menu item was clicked.
* Optional.
*/
button?: number;
}
interface SetTitleDetailsType extends Details {
/**
* The string the browser action should display when moused over.
*/
title: string | null;
}
interface SetIconDetailsType extends Details {
/**
* Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set.
* If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density.
* If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>
* scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported.
* At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.
* imageData = {'19': foo}'
* Optional.
*/
imageData?: ImageDataType | Record<string, ImageDataType>;
/**
* Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set.
* If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density.
* If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>
* scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported.
* At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}'
* Optional.
*/
path?: string | Record<string, string>;
}
interface SetPopupDetailsType extends Details {
/**
* The html file to show in a popup. If set to the empty string (''), no popup is shown.
*/
popup: string | null;
}
interface SetBadgeTextDetailsType extends Details {
/**
* Any number of characters can be passed, but only about four can fit in the space.
*/
text: string | null;
}
interface SetBadgeBackgroundColorDetailsType extends Details {
color: ColorValue;
}
interface SetBadgeTextColorDetailsType extends Details {
color: ColorValue;
}
type OnClickDataModifiersItemEnum = "Shift" | "Alt" | "Command" | "Ctrl" | "MacCtrl";
interface Static {
/**
* Sets the title of the browser action. This shows up in the tooltip.
*
* @param details
*/
setTitle(details: SetTitleDetailsType): Promise<void>;
/**
* Gets the title of the browser action.
*
* @param details
*/
getTitle(details: Details): Promise<string>;
/**
* Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data
* from a canvas element, or as dictionary of either one of those. Either the <b>path</b> or the <b>imageData</b>
* property must be specified.
*
* @param details
*/
setIcon(details: SetIconDetailsType): Promise<void>;
/**
* Sets the html document to be opened as a popup when the user clicks on the browser action's icon.
*
* @param details
*/
setPopup(details: SetPopupDetailsType): Promise<void>;
/**
* Gets the html document set as the popup for this browser action.
*
* @param details
*/
getPopup(details: Details): Promise<string>;
/**
* Sets the badge text for the browser action. The badge is displayed on top of the icon.
*
* @param details
*/
setBadgeText(details: SetBadgeTextDetailsType): Promise<void>;
/**
* Gets the badge text of the browser action. If no tab nor window is specified is specified,
* the global badge text is returned.
*
* @param details
*/
getBadgeText(details: Details): Promise<string>;
/**
* Sets the background color for the badge.
*
* @param details
*/
setBadgeBackgroundColor(details: SetBadgeBackgroundColorDetailsType): Promise<void>;
/**
* Gets the background color of the browser action badge.
*
* @param details
*/
getBadgeBackgroundColor(details: Details): Promise<ColorArray>;
/**
* Sets the text color for the badge.
*
* @param details
*/
setBadgeTextColor(details: SetBadgeTextColorDetailsType): void;
/**
* Gets the text color of the browser action badge.
*
* @param details
*/
getBadgeTextColor(details: Details): void;
/**
* Enables the browser action for a tab. By default, browser actions are enabled.
*
* @param tabId Optional. The id of the tab for which you want to modify the browser action.
*/
enable(tabId?: number): Promise<void>;
/**
* Disables the browser action for a tab.
*
* @param tabId Optional. The id of the tab for which you want to modify the browser action.
*/
disable(tabId?: number): Promise<void>;
/**
* Checks whether the browser action is enabled.
*
* @param details
*/
isEnabled(details: Details): Promise<boolean>;
/**
* Opens the extension popup window in the active window.
*/
openPopup(): Promise<void>;
/**
* Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.
*
* @param tab
* @param info Optional.
*/
onClicked: Events.Event<(tab: Tabs.Tab, info: OnClickData | undefined) => void>;
}
}

107
types/namespaces/activityLog.d.ts vendored Executable file
View File

@ -0,0 +1,107 @@
/**
* Namespace: browser.activityLog
* Generated from Mozilla sources. Do not manually edit!
*
* Monitor extension activity
* Permissions: "activityLog"
*/
import { ExtensionTypes } from "./extensionTypes";
import { Events } from "./events";
export namespace ActivityLog {
interface OnExtensionActivityDetailsType {
/**
* The date string when this call is triggered.
*/
timeStamp: ExtensionTypes.DateType;
/**
* The type of log entry. api_call is a function call made by the extension and api_event is an event callback to the
* extension. content_script is logged when a content script is injected.
*/
type: OnExtensionActivityDetailsTypeTypeEnum;
/**
* The type of view where the activity occurred. Content scripts will not have a viewType.
* Optional.
*/
viewType?: OnExtensionActivityDetailsTypeViewTypeEnum;
/**
* The name of the api call or event, or the script url if this is a content or user script event.
*/
name: string;
data: OnExtensionActivityDetailsTypeDataType;
}
/**
* The type of log entry. api_call is a function call made by the extension and api_event is an event callback to the
* extension. content_script is logged when a content script is injected.
*/
type OnExtensionActivityDetailsTypeTypeEnum = "api_call" | "api_event" | "content_script" | "user_script";
/**
* The type of view where the activity occurred. Content scripts will not have a viewType.
*/
type OnExtensionActivityDetailsTypeViewTypeEnum =
| "background"
| "popup"
| "sidebar"
| "tab"
| "devtools_page"
| "devtools_panel";
/**
* The result of the call.
*/
interface OnExtensionActivityDetailsTypeDataResultType {
[s: string]: unknown;
}
interface OnExtensionActivityDetailsTypeDataType {
/**
* A list of arguments passed to the call.
* Optional.
*/
args?: any[];
/**
* The result of the call.
* Optional.
*/
result?: OnExtensionActivityDetailsTypeDataResultType;
/**
* The tab associated with this event if it is a tab or content script.
* Optional.
*/
tabId?: number;
/**
* If the type is content_script, this is the url of the script that was injected.
* Optional.
*/
url?: string;
}
/**
* Receives an activityItem for each logging event.
*/
interface onExtensionActivityEvent extends Events.Event<(details: OnExtensionActivityDetailsType) => void> {
/**
* Registers an event listener <em>callback</em> to an event.
*
* @param callback Called when an event occurs. The parameters of this function depend on the type of event.
* @param id
*/
addListener(callback: (details: OnExtensionActivityDetailsType) => void, id: string): void;
}
interface Static {
/**
* Receives an activityItem for each logging event.
*/
onExtensionActivity: onExtensionActivityEvent;
}
}

117
types/namespaces/alarms.d.ts vendored Executable file
View File

@ -0,0 +1,117 @@
/**
* Namespace: browser.alarms
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "alarms"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Alarms {
interface Alarm {
/**
* Name of this alarm.
*/
name: string;
/**
* Time when the alarm is scheduled to fire, in milliseconds past the epoch.
*/
scheduledTime: number;
/**
* When present, signals that the alarm triggers periodically after so many minutes.
* Optional.
*/
periodInMinutes?: number;
}
/**
* Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if 'when' is provided),
* after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided instead),
* or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided).
* Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided,
* then the alarm recurs repeatedly after that many minutes.
*/
interface CreateAlarmInfoType {
/**
* Time when the alarm is scheduled to first fire, in milliseconds past the epoch.
* Optional.
*/
when?: number;
/**
* Number of minutes from the current time after which the alarm should first fire.
* Optional.
*/
delayInMinutes?: number;
/**
* Number of minutes after which the alarm should recur repeatedly.
* Optional.
*/
periodInMinutes?: number;
}
interface Static {
/**
* Creates an alarm. After the delay is expired, the onAlarm event is fired. If there is another alarm with the same name
* (or no name if none is specified), it will be cancelled and replaced by this alarm.
*
* @param name Optional. Optional name to identify this alarm. Defaults to the empty string.
* @param alarmInfo Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if 'when'
* is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided instead),
* or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided).
* Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided,
* then the alarm recurs repeatedly after that many minutes.
*/
create(name: string | undefined, alarmInfo: CreateAlarmInfoType): void;
/**
* Creates an alarm. After the delay is expired, the onAlarm event is fired. If there is another alarm with the same name
* (or no name if none is specified), it will be cancelled and replaced by this alarm.
*
* @param alarmInfo Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if 'when'
* is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided instead),
* or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided).
* Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided,
* then the alarm recurs repeatedly after that many minutes.
*/
create(alarmInfo: CreateAlarmInfoType): void;
/**
* Retrieves details about the specified alarm.
*
* @param name Optional. The name of the alarm to get. Defaults to the empty string.
*/
get(name?: string): Promise<Alarm>;
/**
* Gets an array of all the alarms.
*/
getAll(): Promise<Alarm[]>;
/**
* Clears the alarm with the given name.
*
* @param name Optional. The name of the alarm to clear. Defaults to the empty string.
*/
clear(name?: string): Promise<boolean>;
/**
* Clears all alarms.
*/
clearAll(): Promise<boolean>;
/**
* Fired when an alarm has expired. Useful for transient background pages.
*
* @param name The alarm that has expired.
*/
onAlarm: Events.Event<(name: Alarm) => void>;
}
}

316
types/namespaces/bookmarks.d.ts vendored Executable file
View File

@ -0,0 +1,316 @@
/**
* Namespace: browser.bookmarks
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.bookmarks</code> API to create, organize, and otherwise manipulate bookmarks.
* Also see $(topic:override)[Override Pages], which you can use to create a custom Bookmark Manager page.
* Permissions: "bookmarks"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Bookmarks {
/**
* Indicates the reason why this node is unmodifiable. The <var>managed</var> value indicates that this node was configured
* by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user
* and the extension (default).
*/
type BookmarkTreeNodeUnmodifiable = "managed";
/**
* Indicates the type of a BookmarkTreeNode, which can be one of bookmark, folder or separator.
*/
type BookmarkTreeNodeType = "bookmark" | "folder" | "separator";
/**
* A node (either a bookmark or a folder) in the bookmark tree. Child nodes are ordered within their parent folder.
*/
interface BookmarkTreeNode {
/**
* The unique identifier for the node. IDs are unique within the current profile, and they remain valid even after the
* browser is restarted.
*/
id: string;
/**
* The <code>id</code> of the parent folder. Omitted for the root node.
* Optional.
*/
parentId?: string;
/**
* The 0-based position of this node within its parent folder.
* Optional.
*/
index?: number;
/**
* The URL navigated to when a user clicks the bookmark. Omitted for folders.
* Optional.
*/
url?: string;
/**
* The text displayed for the node.
*/
title: string;
/**
* When this node was created, in milliseconds since the epoch (<code>new Date(dateAdded)</code>).
* Optional.
*/
dateAdded?: number;
/**
* When the contents of this folder last changed, in milliseconds since the epoch.
* Optional.
*/
dateGroupModified?: number;
/**
* Indicates the reason why this node is unmodifiable. The <var>managed</var> value indicates that this node was configured
* by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user
* and the extension (default).
* Optional.
*/
unmodifiable?: BookmarkTreeNodeUnmodifiable;
/**
* Indicates the type of the BookmarkTreeNode, which can be one of bookmark, folder or separator.
* Optional.
*/
type?: BookmarkTreeNodeType;
/**
* An ordered list of children of this node.
* Optional.
*/
children?: BookmarkTreeNode[];
}
/**
* Object passed to the create() function.
*/
interface CreateDetails {
/**
* Defaults to the Other Bookmarks folder.
* Optional.
*/
parentId?: string;
/**
* Optional.
*/
index?: number;
/**
* Optional.
*/
title?: string;
/**
* Optional.
*/
url?: string;
/**
* Indicates the type of BookmarkTreeNode to create, which can be one of bookmark, folder or separator.
* Optional.
*/
type?: BookmarkTreeNodeType;
}
/**
* An object specifying properties and values to match when searching. Produces bookmarks matching all properties.
*/
interface SearchQueryC2Type {
/**
* A string of words that are matched against bookmark URLs and titles.
* Optional.
*/
query?: string;
/**
* The URL of the bookmark; matches verbatim. Note that folders have no URL.
* Optional.
*/
url?: string;
/**
* The title of the bookmark; matches verbatim.
* Optional.
*/
title?: string;
}
interface MoveDestinationType {
/**
* Optional.
*/
parentId?: string;
/**
* Optional.
*/
index?: number;
}
interface UpdateChangesType {
/**
* Optional.
*/
title?: string;
/**
* Optional.
*/
url?: string;
}
interface OnRemovedRemoveInfoType {
parentId: string;
index: number;
node: BookmarkTreeNode;
}
interface OnChangedChangeInfoType {
title: string;
/**
* Optional.
*/
url?: string;
}
interface OnMovedMoveInfoType {
parentId: string;
index: number;
oldParentId: string;
oldIndex: number;
}
interface Static {
/**
* Retrieves the specified BookmarkTreeNode(s).
*
* @param idOrIdList A single string-valued id, or an array of string-valued ids
*/
get(idOrIdList: string | string[]): Promise<BookmarkTreeNode[]>;
/**
* Retrieves the children of the specified BookmarkTreeNode id.
*
* @param id
*/
getChildren(id: string): Promise<BookmarkTreeNode[]>;
/**
* Retrieves the recently added bookmarks.
*
* @param numberOfItems The maximum number of items to return.
*/
getRecent(numberOfItems: number): Promise<BookmarkTreeNode[]>;
/**
* Retrieves the entire Bookmarks hierarchy.
*/
getTree(): Promise<BookmarkTreeNode[]>;
/**
* Retrieves part of the Bookmarks hierarchy, starting at the specified node.
*
* @param id The ID of the root of the subtree to retrieve.
*/
getSubTree(id: string): Promise<BookmarkTreeNode[]>;
/**
* Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes
* matching all specified properties.
*
* @param query Either a string of words that are matched against bookmark URLs and titles, or an object. If an object,
* the properties <code>query</code>, <code>url</code>, and <code>title</code> may be specified and bookmarks matching all
* specified properties will be produced.
*/
search(query: string | SearchQueryC2Type): Promise<BookmarkTreeNode[]>;
/**
* Creates a bookmark or folder under the specified parentId. If url is NULL or missing, it will be a folder.
*
* @param bookmark
*/
create(bookmark: CreateDetails): Promise<BookmarkTreeNode>;
/**
* Moves the specified BookmarkTreeNode to the provided location.
*
* @param id
* @param destination
*/
move(id: string, destination: MoveDestinationType): Promise<BookmarkTreeNode>;
/**
* Updates the properties of a bookmark or folder. Specify only the properties that you want to change; unspecified
* properties will be left unchanged. <b>Note:</b> Currently, only 'title' and 'url' are supported.
*
* @param id
* @param changes
*/
update(id: string, changes: UpdateChangesType): Promise<BookmarkTreeNode>;
/**
* Removes a bookmark or an empty bookmark folder.
*
* @param id
*/
remove(id: string): Promise<void>;
/**
* Recursively removes a bookmark folder.
*
* @param id
*/
removeTree(id: string): Promise<void>;
/**
* Fired when a bookmark or folder is created.
*
* @param id
* @param bookmark
*/
onCreated: Events.Event<(id: string, bookmark: BookmarkTreeNode) => void>;
/**
* Fired when a bookmark or folder is removed. When a folder is removed recursively,
* a single notification is fired for the folder, and none for its contents.
*
* @param id
* @param removeInfo
*/
onRemoved: Events.Event<(id: string, removeInfo: OnRemovedRemoveInfoType) => void>;
/**
* Fired when a bookmark or folder changes. <b>Note:</b> Currently, only title and url changes trigger this.
*
* @param id
* @param changeInfo
*/
onChanged: Events.Event<(id: string, changeInfo: OnChangedChangeInfoType) => void>;
/**
* Fired when a bookmark or folder is moved to a different parent folder.
*
* @param id
* @param moveInfo
*/
onMoved: Events.Event<(id: string, moveInfo: OnMovedMoveInfoType) => void>;
}
}

18
types/namespaces/browserAction.d.ts vendored Executable file
View File

@ -0,0 +1,18 @@
/**
* Namespace: browser.browserAction
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "manifest:action", "manifest:browser_action"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Action } from "./action";
export namespace BrowserAction {
interface Static extends Action.Static {
[s: string]: unknown;
}
}

125
types/namespaces/browserSettings.d.ts vendored Executable file
View File

@ -0,0 +1,125 @@
/**
* Namespace: browser.browserSettings
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.browserSettings</code> API to control global settings of the browser.
* Permissions: "browserSettings"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { BrowserSettingsColorManagement } from "./browserSettings_colorManagement";
import { Types } from "./types";
export namespace BrowserSettings {
/**
* How images should be animated in the browser.
*/
type ImageAnimationBehavior = "normal" | "none" | "once";
/**
* After which mouse event context menus should popup.
*/
type ContextMenuMouseEvent = "mouseup" | "mousedown";
/**
* Color management mode.
*/
type ColorManagementMode = "off" | "full" | "tagged_only";
interface Static {
/**
* Allows or disallows pop-up windows from opening in response to user events.
*/
allowPopupsForUserEvents: Types.Setting;
/**
* Enables or disables the browser cache.
*/
cacheEnabled: Types.Setting;
/**
* This boolean setting controls whether the selected tab can be closed with a double click.
*/
closeTabsByDoubleClick: Types.Setting;
/**
* Controls after which mouse event context menus popup. This setting's value is of type ContextMenuMouseEvent,
* which has possible values of <code>mouseup</code> and <code>mousedown</code>.
*/
contextMenuShowEvent: Types.Setting;
/**
* Returns the value of the overridden home page. Read-only.
*/
homepageOverride: Types.Setting;
/**
* Controls the behaviour of image animation in the browser. This setting's value is of type ImageAnimationBehavior,
* defaulting to <code>normal</code>.
*/
imageAnimationBehavior: Types.Setting;
/**
* Returns the value of the overridden new tab page. Read-only.
*/
newTabPageOverride: Types.Setting;
/**
* Controls where new tabs are opened. `afterCurrent` will open all new tabs next to the current tab,
* `relatedAfterCurrent` will open only related tabs next to the current tab, and `atEnd` will open all tabs at the end of
* the tab strip. The default is `relatedAfterCurrent`.
*/
newTabPosition: Types.Setting;
/**
* This boolean setting controls whether bookmarks are opened in the current tab or in a new tab.
*/
openBookmarksInNewTabs: Types.Setting;
/**
* This boolean setting controls whether search results are opened in the current tab or in a new tab.
*/
openSearchResultsInNewTabs: Types.Setting;
/**
* This boolean setting controls whether urlbar results are opened in the current tab or in a new tab.
*/
openUrlbarResultsInNewTabs: Types.Setting;
/**
* Disables webAPI notifications.
*/
webNotificationsDisabled: Types.Setting;
/**
* This setting controls whether the user-chosen colors override the page's colors.
*/
overrideDocumentColors: Types.Setting;
/**
* This setting controls whether a light or dark color scheme overrides the page's preferred color scheme.
*/
overrideContentColorScheme: Types.Setting;
/**
* This setting controls whether the document's fonts are used.
*/
useDocumentFonts: Types.Setting;
/**
* This boolean setting controls whether zoom is applied to the full page or to text only.
*/
zoomFullPage: Types.Setting;
/**
* This boolean setting controls whether zoom is applied on a per-site basis or to the current tab only. If privacy.
* resistFingerprinting is true, this setting has no effect and zoom is applied to the current tab only.
*/
zoomSiteSpecific: Types.Setting;
colorManagement: BrowserSettingsColorManagement.Static;
}
}

View File

@ -0,0 +1,33 @@
/**
* Namespace: browser.browserSettings.colorManagement
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browserSettings.colorManagement</code> API to query and set items related to color management.
* Permissions: "browserSettings"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Types } from "./types";
export namespace BrowserSettingsColorManagement {
interface Static {
/**
* This setting controls the mode used for color management and must be a string from $(ref:browserSettings.
* ColorManagementMode)
*/
mode: Types.Setting;
/**
* This boolean setting controls whether or not native sRGB color management is used.
*/
useNativeSRGB: Types.Setting;
/**
* This boolean setting controls whether or not the WebRender compositor is used.
*/
useWebRenderCompositor: Types.Setting;
}
}

243
types/namespaces/browsingData.d.ts vendored Executable file
View File

@ -0,0 +1,243 @@
/**
* Namespace: browser.browsingData
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>chrome.browsingData</code> API to remove browsing data from a user's local profile.
* Permissions: "browsingData"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { ExtensionTypes } from "./extensionTypes";
export namespace BrowsingData {
/**
* Options that determine exactly what data will be removed.
*/
interface RemovalOptions {
/**
* Remove data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the <code>
* getTime</code> method of the JavaScript <code>Date</code> object). If absent, defaults to 0 (which would remove all
* browsing data).
* Optional.
*/
since?: ExtensionTypes.DateType;
/**
* Only remove data associated with these hostnames (only applies to cookies and localStorage).
* Optional.
*/
hostnames?: string[];
/**
* Only remove data associated with this specific cookieStoreId.
* Optional.
*/
cookieStoreId?: string;
/**
* An object whose properties specify which origin types ought to be cleared. If this object isn't specified,
* it defaults to clearing only "unprotected" origins. Please ensure that you <em>really</em>
* want to remove application data before adding 'protectedWeb' or 'extensions'.
* Optional.
*/
originTypes?: RemovalOptionsOriginTypesType;
}
/**
* A set of data types. Missing data types are interpreted as <code>false</code>.
*/
interface DataTypeSet {
/**
* The browser's cache. Note: when removing data, this clears the <em>entire</em> cache: it is not limited to the range you
* specify.
* Optional.
*/
cache?: boolean;
/**
* The browser's cookies.
* Optional.
*/
cookies?: boolean;
/**
* The browser's download list.
* Optional.
*/
downloads?: boolean;
/**
* The browser's stored form data.
* Optional.
*/
formData?: boolean;
/**
* The browser's history.
* Optional.
*/
history?: boolean;
/**
* Websites' IndexedDB data.
* Optional.
*/
indexedDB?: boolean;
/**
* Websites' local storage data.
* Optional.
*/
localStorage?: boolean;
/**
* Server-bound certificates.
* Optional.
*/
serverBoundCertificates?: boolean;
/**
* Stored passwords.
* Optional.
*/
passwords?: boolean;
/**
* Plugins' data.
* Optional.
*/
pluginData?: boolean;
/**
* Service Workers.
* Optional.
*/
serviceWorkers?: boolean;
}
interface SettingsCallbackResultType {
options: RemovalOptions;
/**
* All of the types will be present in the result, with values of <code>true</code> if they are both selected to be removed
* and permitted to be removed, otherwise <code>false</code>.
*/
dataToRemove: DataTypeSet;
/**
* All of the types will be present in the result, with values of <code>true</code> if they are permitted to be removed (e.
* g., by enterprise policy) and <code>false</code> if not.
*/
dataRemovalPermitted: DataTypeSet;
}
/**
* An object whose properties specify which origin types ought to be cleared. If this object isn't specified,
* it defaults to clearing only "unprotected" origins. Please ensure that you <em>really</em>
* want to remove application data before adding 'protectedWeb' or 'extensions'.
*/
interface RemovalOptionsOriginTypesType {
/**
* Normal websites.
* Optional.
*/
unprotectedWeb?: boolean;
/**
* Websites that have been installed as hosted applications (be careful!).
* Optional.
*/
protectedWeb?: boolean;
/**
* Extensions and packaged applications a user has installed (be _really_ careful!).
* Optional.
*/
extension?: boolean;
}
interface Static {
/**
* Reports which types of data are currently selected in the 'Clear browsing data' settings UI.
* Note: some of the data types included in this API are not available in the settings UI,
* and some UI settings control more than one data type listed here.
*/
settings(): Promise<SettingsCallbackResultType>;
/**
* Clears various types of browsing data stored in a user's profile.
*
* @param options
* @param dataToRemove The set of data types to remove.
* @returns Called when deletion has completed.
*/
remove(options: RemovalOptions, dataToRemove: DataTypeSet): Promise<void>;
/**
* Clears the browser's cache.
*
* @param options
* @returns Called when the browser's cache has been cleared.
*/
removeCache(options: RemovalOptions): Promise<void>;
/**
* Clears the browser's cookies and server-bound certificates modified within a particular timeframe.
*
* @param options
* @returns Called when the browser's cookies and server-bound certificates have been cleared.
*/
removeCookies(options: RemovalOptions): Promise<void>;
/**
* Clears the browser's list of downloaded files (<em>not</em> the downloaded files themselves).
*
* @param options
* @returns Called when the browser's list of downloaded files has been cleared.
*/
removeDownloads(options: RemovalOptions): Promise<void>;
/**
* Clears the browser's stored form data (autofill).
*
* @param options
* @returns Called when the browser's form data has been cleared.
*/
removeFormData(options: RemovalOptions): Promise<void>;
/**
* Clears the browser's history.
*
* @param options
* @returns Called when the browser's history has cleared.
*/
removeHistory(options: RemovalOptions): Promise<void>;
/**
* Clears websites' local storage data.
*
* @param options
* @returns Called when websites' local storage has been cleared.
*/
removeLocalStorage(options: RemovalOptions): Promise<void>;
/**
* Clears plugins' data.
*
* @param options
* @returns Called when plugins' data has been cleared.
*/
removePluginData(options: RemovalOptions): Promise<void>;
/**
* Clears the browser's stored passwords.
*
* @param options
* @returns Called when the browser's passwords have been cleared.
*/
removePasswords(options: RemovalOptions): Promise<void>;
}
}

58
types/namespaces/captivePortal.d.ts vendored Executable file
View File

@ -0,0 +1,58 @@
/**
* Namespace: browser.captivePortal
* Generated from Mozilla sources. Do not manually edit!
*
* This API provides the ability detect the captive portal state of the users connection.
* Permissions: "captivePortal"
*/
import { Events } from "./events";
import { Types } from "./types";
export namespace CaptivePortal {
interface OnStateChangedDetailsType {
/**
* The current captive portal state.
*/
state: OnStateChangedDetailsTypeStateEnum;
}
type OnConnectivityAvailableStatusEnum = "captive" | "clear";
/**
* The current captive portal state.
*/
type OnStateChangedDetailsTypeStateEnum = "unknown" | "not_captive" | "unlocked_portal" | "locked_portal";
interface Static {
/**
* Returns the current portal state, one of `unknown`, `not_captive`, `unlocked_portal`, `locked_portal`.
*/
getState(): void;
/**
* Returns the time difference between NOW and the last time a request was completed in milliseconds.
*/
getLastChecked(): void;
/**
* Fired when the captive portal state changes.
*
* @param details
*/
onStateChanged: Events.Event<(details: OnStateChangedDetailsType) => void>;
/**
* This notification will be emitted when the captive portal service has determined that we can connect to the internet.
* The service will pass either `captive` if there is an unlocked captive portal present,
* or `clear` if no captive portal was detected.
*
* @param status
*/
onConnectivityAvailable: Events.Event<(status: OnConnectivityAvailableStatusEnum) => void>;
/**
* Return the canonical captive-portal detection URL. Read-only.
*/
canonicalURL: Types.Setting;
}
}

25
types/namespaces/clipboard.d.ts vendored Executable file
View File

@ -0,0 +1,25 @@
/**
* Namespace: browser.clipboard
* Generated from Mozilla sources. Do not manually edit!
*
* Offers the ability to write to the clipboard. Reading is not supported because the clipboard can already be read through
* the standard web platform APIs.
* Permissions: "clipboardWrite"
*/
export namespace Clipboard {
/**
* The type of imageData.
*/
type SetImageDataImageTypeEnum = "jpeg" | "png";
interface Static {
/**
* Copy an image to the clipboard. The image is re-encoded before it is written to the clipboard. If the image is invalid,
* the clipboard is not modified.
*
* @param imageData The image data to be copied.
* @param imageType The type of imageData.
*/
setImageData(imageData: ArrayBuffer, imageType: SetImageDataImageTypeEnum): Promise<void>;
}
}

87
types/namespaces/commands.d.ts vendored Executable file
View File

@ -0,0 +1,87 @@
/**
* Namespace: browser.commands
* Generated from Mozilla sources. Do not manually edit!
*
* Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example,
* an action to open the browser action or send a command to the xtension.
* Permissions: "manifest:commands"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Commands {
interface Command {
/**
* The name of the Extension Command
* Optional.
*/
name?: string;
/**
* The Extension Command description
* Optional.
*/
description?: string;
/**
* The shortcut active for this command, or blank if not active.
* Optional.
*/
shortcut?: string;
}
/**
* The new description for the command.
*/
interface UpdateDetailType {
/**
* The name of the command.
*/
name: string;
/**
* The new description for the command.
* Optional.
*/
description?: string;
/**
* Optional.
*/
shortcut?: string;
}
interface Static {
/**
* Update the details of an already defined command.
*
* @param detail The new description for the command.
*/
update(detail: UpdateDetailType): Promise<void>;
/**
* Reset a command's details to what is specified in the manifest.
*
* @param name The name of the command.
*/
reset(name: string): Promise<void>;
/**
* Returns all the registered extension commands for this extension and their shortcut (if active).
*
* @returns Called to return the registered commands.
*/
getAll(): Promise<Command[]>;
/**
* Fired when a registered command is activated using a keyboard shortcut.
*
* @param command
*/
onCommand: Events.Event<(command: string) => void>;
}
}

86
types/namespaces/contentScripts.d.ts vendored Executable file
View File

@ -0,0 +1,86 @@
/**
* Namespace: browser.contentScripts
* Generated from Mozilla sources. Do not manually edit!
*
* Comments found in source JSON schema files:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Manifest } from "./manifest";
import { ExtensionTypes } from "./extensionTypes";
export namespace ContentScripts {
/**
* Details of a content script registered programmatically
*/
interface RegisteredContentScriptOptions {
matches: Manifest.MatchPattern[];
/**
* Optional.
*/
excludeMatches?: Manifest.MatchPattern[];
/**
* Optional.
*/
includeGlobs?: string[];
/**
* Optional.
*/
excludeGlobs?: string[];
/**
* The list of CSS files to inject
* Optional.
*/
css?: ExtensionTypes.ExtensionFileOrCode[];
/**
* The list of JS files to inject
* Optional.
*/
js?: ExtensionTypes.ExtensionFileOrCode[];
/**
* If allFrames is <code>true</code>, implies that the JavaScript or CSS should be injected into all frames of current page.
* By default, it's <code>false</code> and is only injected into the top frame.
* Optional.
*/
allFrames?: boolean;
/**
* If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has
* access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is <code>false</code>.
* Optional.
*/
matchAboutBlank?: boolean;
/**
* The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle".
* Optional.
*/
runAt?: ExtensionTypes.RunAt;
}
/**
* An object that represents a content script registered programmatically
*/
interface RegisteredContentScript {
/**
* Unregister a content script registered programmatically
*/
unregister(): Promise<void>;
}
interface Static {
/**
* Register a content script programmatically
*
* @param contentScriptOptions
*/
register(contentScriptOptions: RegisteredContentScriptOptions): Promise<RegisteredContentScript>;
}
}

20
types/namespaces/contextMenus.d.ts vendored Executable file
View File

@ -0,0 +1,20 @@
/**
* Namespace: browser.contextMenus
* Generated from Mozilla sources. Do not manually edit!
*
* Use the browser.contextMenus API to add items to the browser's context menu. You can choose what types of objects your
* context menu additions apply to, such as images, hyperlinks, and pages.
* Permissions: "contextMenus"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Menus } from "./menus";
export namespace ContextMenus {
interface Static extends Menus.Static {
[s: string]: unknown;
}
}

184
types/namespaces/contextualIdentities.d.ts vendored Executable file
View File

@ -0,0 +1,184 @@
/**
* Namespace: browser.contextualIdentities
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.contextualIdentities</code> API to query and modify contextual identity, also called as containers.
* Permissions: "contextualIdentities"
*
* Comments found in source JSON schema files:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Events } from "./events";
export namespace ContextualIdentities {
/**
* Represents information about a contextual identity.
*/
interface ContextualIdentity {
/**
* The name of the contextual identity.
*/
name: string;
/**
* The icon name of the contextual identity.
*/
icon: string;
/**
* The icon url of the contextual identity.
*/
iconUrl: string;
/**
* The color name of the contextual identity.
*/
color: string;
/**
* The color hash of the contextual identity.
*/
colorCode: string;
/**
* The cookie store ID of the contextual identity.
*/
cookieStoreId: string;
}
/**
* Information to filter the contextual identities being retrieved.
*/
interface QueryDetailsType {
/**
* Filters the contextual identity by name.
* Optional.
*/
name?: string;
}
/**
* Details about the contextual identity being created.
*/
interface CreateDetailsType {
/**
* The name of the contextual identity.
*/
name: string;
/**
* The color of the contextual identity.
*/
color: string;
/**
* The icon of the contextual identity.
*/
icon: string;
}
/**
* Details about the contextual identity being created.
*/
interface UpdateDetailsType {
/**
* The name of the contextual identity.
* Optional.
*/
name?: string;
/**
* The color of the contextual identity.
* Optional.
*/
color?: string;
/**
* The icon of the contextual identity.
* Optional.
*/
icon?: string;
}
interface OnUpdatedChangeInfoType {
/**
* Contextual identity that has been updated
*/
contextualIdentity: ContextualIdentity;
}
interface OnCreatedChangeInfoType {
/**
* Contextual identity that has been created
*/
contextualIdentity: ContextualIdentity;
}
interface OnRemovedChangeInfoType {
/**
* Contextual identity that has been removed
*/
contextualIdentity: ContextualIdentity;
}
interface Static {
/**
* Retrieves information about a single contextual identity.
*
* @param cookieStoreId The ID of the contextual identity cookie store.
*/
get(cookieStoreId: string): Promise<ContextualIdentity>;
/**
* Retrieves all contextual identities
*
* @param details Information to filter the contextual identities being retrieved.
*/
query(details: QueryDetailsType): Promise<ContextualIdentity[]>;
/**
* Creates a contextual identity with the given data.
*
* @param details Details about the contextual identity being created.
*/
create(details: CreateDetailsType): Promise<ContextualIdentity>;
/**
* Updates a contextual identity with the given data.
*
* @param cookieStoreId The ID of the contextual identity cookie store.
* @param details Details about the contextual identity being created.
*/
update(cookieStoreId: string, details: UpdateDetailsType): Promise<ContextualIdentity>;
/**
* Deletes a contetual identity by its cookie Store ID.
*
* @param cookieStoreId The ID of the contextual identity cookie store.
*/
remove(cookieStoreId: string): Promise<ContextualIdentity>;
/**
* Fired when a container is updated.
*
* @param changeInfo
*/
onUpdated: Events.Event<(changeInfo: OnUpdatedChangeInfoType) => void>;
/**
* Fired when a new container is created.
*
* @param changeInfo
*/
onCreated: Events.Event<(changeInfo: OnCreatedChangeInfoType) => void>;
/**
* Fired when a container is removed.
*
* @param changeInfo
*/
onRemoved: Events.Event<(changeInfo: OnRemovedChangeInfoType) => void>;
}
}

450
types/namespaces/cookies.d.ts vendored Executable file
View File

@ -0,0 +1,450 @@
/**
* Namespace: browser.cookies
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.cookies</code> API to query and modify cookies, and to be notified when they change.
* Permissions: "cookies"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Cookies {
/**
* A cookie's 'SameSite' state (https://tools.ietf.org/html/draft-west-first-party-cookies).
* 'no_restriction' corresponds to a cookie set without a 'SameSite' attribute, 'lax' to 'SameSite=Lax',
* and 'strict' to 'SameSite=Strict'.
*/
type SameSiteStatus = "no_restriction" | "lax" | "strict";
/**
* The description of the storage partition of a cookie. This object may be omitted (null) if a cookie is not partitioned.
*/
interface PartitionKey {
/**
* The first-party URL of the cookie, if the cookie is in storage partitioned by the top-level site.
* Optional.
*/
topLevelSite?: string;
}
/**
* Represents information about an HTTP cookie.
*/
interface Cookie {
/**
* The name of the cookie.
*/
name: string;
/**
* The value of the cookie.
*/
value: string;
/**
* The domain of the cookie (e.g. "www.google.com", "example.com").
*/
domain: string;
/**
* True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie).
*/
hostOnly: boolean;
/**
* The path of the cookie.
*/
path: string;
/**
* True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS).
*/
secure: boolean;
/**
* True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts).
*/
httpOnly: boolean;
/**
* The cookie's same-site status (i.e. whether the cookie is sent with cross-site requests).
*/
sameSite: SameSiteStatus;
/**
* True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date.
*/
session: boolean;
/**
* The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies.
* Optional.
*/
expirationDate?: number;
/**
* The ID of the cookie store containing this cookie, as provided in getAllCookieStores().
*/
storeId: string;
/**
* The first-party domain of the cookie.
*/
firstPartyDomain: string;
/**
* The cookie's storage partition, if any. null if not partitioned.
* Optional.
*/
partitionKey?: PartitionKey;
}
/**
* Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a
* non-incognito window.
*/
interface CookieStore {
/**
* The unique identifier for the cookie store.
*/
id: string;
/**
* Identifiers of all the browser tabs that share this cookie store.
*/
tabIds: number[];
/**
* Indicates if this is an incognito cookie store
*/
incognito: boolean;
}
/**
* The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to
* $(ref:cookies.remove), "cause" will be "explicit". If a cookie was automatically removed due to expiry,
* "cause" will be "expired". If a cookie was removed due to being overwritten with an already-expired expiration date,
* "cause" will be set to "expired_overwrite". If a cookie was automatically removed due to garbage collection,
* "cause" will be "evicted". If a cookie was automatically removed due to a "set" call that overwrote it,
* "cause" will be "overwrite". Plan your response accordingly.
*/
type OnChangedCause = "evicted" | "expired" | "explicit" | "expired_overwrite" | "overwrite";
/**
* Details to identify the cookie being retrieved.
*/
interface GetDetailsType {
/**
* The URL with which the cookie to retrieve is associated. This argument may be a full URL,
* in which case any data following the URL path (e.g. the query string) is simply ignored.
* If host permissions for this URL are not specified in the manifest file, the API call will fail.
*/
url: string;
/**
* The name of the cookie to retrieve.
*/
name: string;
/**
* The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store
* will be used.
* Optional.
*/
storeId?: string;
/**
* The first-party domain which the cookie to retrieve is associated. This attribute is required if First-Party Isolation
* is enabled.
* Optional.
*/
firstPartyDomain?: string;
/**
* The storage partition, if the cookie is part of partitioned storage. By default, only non-partitioned cookies are
* returned.
* Optional.
*/
partitionKey?: PartitionKey;
}
/**
* Information to filter the cookies being retrieved.
*/
interface GetAllDetailsType {
/**
* Restricts the retrieved cookies to those that would match the given URL.
* Optional.
*/
url?: string;
/**
* Filters the cookies by name.
* Optional.
*/
name?: string;
/**
* Restricts the retrieved cookies to those whose domains match or are subdomains of this one.
* Optional.
*/
domain?: string;
/**
* Restricts the retrieved cookies to those whose path exactly matches this string.
* Optional.
*/
path?: string;
/**
* Filters the cookies by their Secure property.
* Optional.
*/
secure?: boolean;
/**
* Filters out session vs. persistent cookies.
* Optional.
*/
session?: boolean;
/**
* The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used.
* Optional.
*/
storeId?: string;
/**
* Restricts the retrieved cookies to those whose first-party domains match this one.
* This attribute is required if First-Party Isolation is enabled. To not filter by a specific first-party domain,
* use `null` or `undefined`.
* Optional.
*/
firstPartyDomain?: string | null;
/**
* Selects a specific storage partition to look up cookies. Defaults to null, in which case only non-partitioned cookies
* are retrieved. If an object iis passed, partitioned cookies are also included, and filtered based on the keys present in
* the given PartitionKey description. An empty object ({}) returns all cookies (partitioned + unpartitioned),
* a non-empty object (e.g. {topLevelSite: '...'}) only returns cookies whose partition match all given attributes.
* Optional.
*/
partitionKey?: PartitionKey;
}
/**
* Details about the cookie being set.
*/
interface SetDetailsType {
/**
* The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of
* the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail.
*/
url: string;
/**
* The name of the cookie. Empty by default if omitted.
* Optional.
*/
name?: string;
/**
* The value of the cookie. Empty by default if omitted.
* Optional.
*/
value?: string;
/**
* The domain of the cookie. If omitted, the cookie becomes a host-only cookie.
* Optional.
*/
domain?: string;
/**
* The path of the cookie. Defaults to the path portion of the url parameter.
* Optional.
*/
path?: string;
/**
* Whether the cookie should be marked as Secure. Defaults to false.
* Optional.
*/
secure?: boolean;
/**
* Whether the cookie should be marked as HttpOnly. Defaults to false.
* Optional.
*/
httpOnly?: boolean;
/**
* The cookie's same-site status.
* Optional.
*/
sameSite?: SameSiteStatus;
/**
* The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted,
* the cookie becomes a session cookie.
* Optional.
*/
expirationDate?: number;
/**
* The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's
* cookie store.
* Optional.
*/
storeId?: string;
/**
* The first-party domain of the cookie. This attribute is required if First-Party Isolation is enabled.
* Optional.
*/
firstPartyDomain?: string;
/**
* The storage partition, if the cookie is part of partitioned storage. By default, non-partitioned storage is used.
* Optional.
*/
partitionKey?: PartitionKey;
}
/**
* Information to identify the cookie to remove.
*/
interface RemoveDetailsType {
/**
* The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file,
* the API call will fail.
*/
url: string;
/**
* The name of the cookie to remove.
*/
name: string;
/**
* The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in the current
* execution context's cookie store.
* Optional.
*/
storeId?: string;
/**
* The first-party domain associated with the cookie. This attribute is required if First-Party Isolation is enabled.
* Optional.
*/
firstPartyDomain?: string;
/**
* The storage partition, if the cookie is part of partitioned storage. By default, non-partitioned storage is used.
* Optional.
*/
partitionKey?: PartitionKey;
}
/**
* Contains details about the cookie that's been removed. If removal failed for any reason, this will be "null",
* and $(ref:runtime.lastError) will be set.
*/
interface RemoveCallbackDetailsType {
/**
* The URL associated with the cookie that's been removed.
*/
url: string;
/**
* The name of the cookie that's been removed.
*/
name: string;
/**
* The ID of the cookie store from which the cookie was removed.
*/
storeId: string;
/**
* The first-party domain associated with the cookie that's been removed.
*/
firstPartyDomain: string;
/**
* The storage partition, if the cookie is part of partitioned storage. null if not partitioned.
* Optional.
*/
partitionKey?: PartitionKey;
}
interface OnChangedChangeInfoType {
/**
* True if a cookie was removed.
*/
removed: boolean;
/**
* Information about the cookie that was set or removed.
*/
cookie: Cookie;
/**
* The underlying reason behind the cookie's change.
*/
cause: OnChangedCause;
}
interface Static {
/**
* Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL,
* the one with the longest path will be returned. For cookies with the same path length,
* the cookie with the earliest creation time will be returned.
*
* @param details Details to identify the cookie being retrieved.
*/
get(details: GetDetailsType): Promise<Cookie>;
/**
* Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted,
* with those with the longest path first. If multiple cookies have the same path length,
* those with the earliest creation time will be first.
*
* @param details Information to filter the cookies being retrieved.
*/
getAll(details: GetAllDetailsType): Promise<Cookie[]>;
/**
* Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.
*
* @param details Details about the cookie being set.
*/
set(details: SetDetailsType): Promise<Cookie>;
/**
* Deletes a cookie by name.
*
* @param details Information to identify the cookie to remove.
*/
remove(details: RemoveDetailsType): Promise<RemoveCallbackDetailsType>;
/**
* Lists all existing cookie stores.
*/
getAllCookieStores(): Promise<CookieStore[]>;
/**
* Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a
* two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of
* "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with
* "cause" "explicit".
*
* @param changeInfo
*/
onChanged: Events.Event<(changeInfo: OnChangedChangeInfoType) => void>;
}
}

179
types/namespaces/declarativeContent.d.ts vendored Executable file
View File

@ -0,0 +1,179 @@
/**
* Namespace: browser.declarativeContent
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>chrome.declarativeContent</code> API to take actions depending on the content of a page,
* without requiring permission to read the page's content.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace DeclarativeContent {
/**
* See <a href="https://developer.mozilla.org/en-US/docs/Web/API/ImageData">https://developer.mozilla.
* org/en-US/docs/Web/API/ImageData</a>.
*/
interface ImageDataType extends ImageData {
[s: string]: unknown;
}
/**
* Matches the state of a web page based on various criteria.
*/
interface PageStateMatcher {
/**
* Matches if the conditions of the <code>UrlFilter</code> are fulfilled for the top-level URL of the page.
* Optional.
*/
pageUrl?: Events.UrlFilter;
/**
* Matches if all of the CSS selectors in the array match displayed elements in a frame with the same origin as the page's
* main frame. All selectors in this array must be <a href="http://www.w3.org/TR/selectors4/#compound">
* compound selectors</a> to speed up matching. Note: Listing hundreds of CSS selectors or listing CSS selectors that match
* hundreds of times per page can slow down web sites.
* Optional.
*/
css?: string[];
/**
* Matches if the bookmarked state of the page is equal to the specified value. Requres the <a href='declare_permissions'>
* bookmarks permission</a>.
* Optional.
*/
isBookmarked?: boolean;
}
/**
* Please use ShowAction.
*/
type ShowPageAction = never;
/**
* Declarative event action that shows the extension's toolbar action ($(ref:pageAction page action)
* or $(ref:browserAction browser action)) while the corresponding conditions are met.
* This action can be used without <a href="declare_permissions#host-permissions">host permissions</a>.
* If the extension has the <a href="activeTab.html">activeTab</a> permission, clicking the page action grants access to
* the active tab.
*/
interface ShowAction {
[s: string]: unknown;
}
/**
* Declarative event action that sets the n-<abbr title="device-independent pixel">dip</abbr>
* square icon for the extension's $(ref:pageAction page action) or $(ref:browserAction browser action)
* while the corresponding conditions are met. This action can be used without <a href="declare_permissions.
* html#host-permissions">host permissions</a>, but the extension must have a page or browser action.<p>
* Exactly one of <code>imageData</code> or <code>path</code> must be specified. Both are dictionaries mapping a number of
* pixels to an image representation. The image representation in <code>imageData</code> is an <a href="https://developer.
* mozilla.org/en-US/docs/Web/API/ImageData">ImageData</a> object; for example, from a <code>canvas</code> element,
* while the image representation in <code>path</code> is the path to an image file relative to the extension's manifest.
* If <code>scale</code> screen pixels fit into a device-independent pixel, the <code>scale * n</code> icon is used.
* If that scale is missing, another image is resized to the required size.</p>
*/
interface SetIcon {
/**
* Either an <code>ImageData</code> object or a dictionary {size -> ImageData} representing an icon to be set.
* If the icon is specified as a dictionary, the image used is chosen depending on the screen's pixel density.
* If the number of image pixels that fit into one screen space unit equals <code>scale</code>,
* then an image with size <code>scale * n</code> is selected, where <i>n</i> is the size of the icon in the UI.
* At least one image must be specified. Note that <code>details.imageData = foo</code> is equivalent to <code>details.
* imageData = {'16': foo}</code>.
* Optional.
*/
imageData?: ImageDataType | SetIconImageDataC2Type;
}
/**
* Declarative event action that injects a content script. <p><b>WARNING:</b> This action is still experimental and is not
* supported on stable builds of Chrome.</p>
*/
interface RequestContentScript {
/**
* Names of CSS files to be injected as a part of the content script.
* Optional.
*/
css?: string[];
/**
* Names of JavaScript files to be injected as a part of the content script.
* Optional.
*/
js?: string[];
/**
* Whether the content script runs in all frames of the matching page, or in only the top frame. Default is <code>
* false</code>.
* Optional.
*/
allFrames?: boolean;
/**
* Whether to insert the content script on <code>about:blank</code> and <code>about:srcdoc</code>. Default is <code>
* false</code>.
* Optional.
*/
matchAboutBlank?: boolean;
}
interface Rule<TCondition, TAction> {
/**
* List of conditions that can trigger the actions.
*/
conditions: TCondition[];
/**
* List of actions that are triggered if one of the conditions is fulfilled.
*/
actions: TAction[];
}
/**
* An object which allows the addition and removal of rules for declarative content.
*/
interface RuleEvent<TCondition, TAction> {
/**
* Registers rules to handle events.
*
* @param rules Rules to be registered. These do not replace previously registered rules.
*/
addRules(rules: Array<Rule<TCondition, TAction>>): void;
/**
* Fetches currently registered rules.
*
* @param rules Optional. Rule ids to fetch.
* @param callback Optional. Called when rules have been fetched.
*/
getRules(rules?: string[], callback?: (rules: Array<Rule<TCondition, TAction>>) => void): void;
/**
* Unregisters currently registered rules.
*
* @param rules Optional. Rule ids to be unregistered.
* @param callback Optional. Called when rules were unregistered.
*/
removeRules(rules?: string[], callback?: () => void): void;
}
interface SetIconImageDataC2Type {
[s: string]: unknown;
}
interface Static {
PageStateMatcher: { new (options?: PageStateMatcher): PageStateMatcher };
ShowAction: { new (options?: ShowAction): ShowAction };
SetIcon: { new (options?: SetIcon): SetIcon };
RequestContentScript: { new (options?: RequestContentScript): RequestContentScript };
onPageChanged: RuleEvent<PageStateMatcher, RequestContentScript | SetIcon | ShowPageAction | ShowAction>;
}
}

17
types/namespaces/devtools.d.ts vendored Executable file
View File

@ -0,0 +1,17 @@
/**
* Namespace: browser.devtools
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "manifest:devtools_page"
*/
import { DevtoolsInspectedWindow } from "./devtools_inspectedWindow";
import { DevtoolsNetwork } from "./devtools_network";
import { DevtoolsPanels } from "./devtools_panels";
export namespace Devtools {
interface Static {
inspectedWindow: DevtoolsInspectedWindow.Static;
network: DevtoolsNetwork.Static;
panels: DevtoolsPanels.Static;
}
}

123
types/namespaces/devtools_inspectedWindow.d.ts vendored Executable file
View File

@ -0,0 +1,123 @@
/**
* Namespace: browser.devtools.inspectedWindow
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>chrome.devtools.inspectedWindow</code> API to interact with the inspected window: obtain the tab ID for
* the inspected page, evaluate the code in the context of the inspected window, reload the page,
* or obtain the list of resources within the page.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
export namespace DevtoolsInspectedWindow {
/**
* A resource within the inspected page, such as a document, a script, or an image.
*/
interface Resource {
/**
* The URL of the resource.
*/
url: string;
}
/**
* The options parameter can contain one or more options.
*/
interface EvalOptionsType {
[s: string]: unknown;
}
/**
* An object providing details if an exception occurred while evaluating the expression.
*/
interface EvalCallbackExceptionInfoType {
/**
* Set if the error occurred on the DevTools side before the expression is evaluated.
*/
isError: boolean;
/**
* Set if the error occurred on the DevTools side before the expression is evaluated.
*/
code: string;
/**
* Set if the error occurred on the DevTools side before the expression is evaluated.
*/
description: string;
/**
* Set if the error occurred on the DevTools side before the expression is evaluated,
* contains the array of the values that may be substituted into the description string to provide more information about
* the cause of the error.
*/
details: any[];
/**
* Set if the evaluated code produces an unhandled exception.
*/
isException: boolean;
/**
* Set if the evaluated code produces an unhandled exception.
*/
value: string;
}
interface ReloadReloadOptionsType {
/**
* When true, the loader will bypass the cache for all inspected page resources loaded before the <code>load</code>
* event is fired. The effect is similar to pressing Ctrl+Shift+R in the inspected window or within the Developer Tools
* window.
* Optional.
*/
ignoreCache?: boolean;
/**
* If specified, the string will override the value of the <code>User-Agent</code> HTTP header that's sent while loading
* the resources of the inspected page. The string will also override the value of the <code>navigator.userAgent</code>
* property that's returned to any scripts that are running within the inspected page.
* Optional.
*/
userAgent?: string;
/**
* If specified, the script will be injected into every frame of the inspected page immediately upon load,
* before any of the frame's scripts. The script will not be injected after subsequent reloads&mdash;for example,
* if the user presses Ctrl+R.
* Optional.
*/
injectedScript?: string;
}
interface Static {
/**
* Evaluates a JavaScript expression in the context of the main frame of the inspected page.
* The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown.
* The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation.
* In either case, the <code>result</code> parameter of the callback is <code>undefined</code>.
* In the case of a DevTools-side error, the <code>isException</code> parameter is non-null and has <code>isError</code>
* set to true and <code>code</code> set to an error code. In the case of a JavaScript error, <code>isException</code>
* is set to true and <code>value</code> is set to the string value of thrown object.
*
* @param expression An expression to evaluate.
* @param options Optional. The options parameter can contain one or more options.
* @returns A function called when evaluation completes.
*/
eval(expression: string, options?: EvalOptionsType): Promise<[any, EvalCallbackExceptionInfoType]>;
/**
* Reloads the inspected page.
*
* @param reloadOptions Optional.
*/
reload(reloadOptions?: ReloadReloadOptionsType): void;
/**
* The ID of the tab being inspected. This ID may be used with chrome.tabs.* API.
*/
tabId: number;
}
}

57
types/namespaces/devtools_network.d.ts vendored Executable file
View File

@ -0,0 +1,57 @@
/**
* Namespace: browser.devtools.network
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>chrome.devtools.network</code> API to retrieve the information about network requests displayed by the
* Developer Tools in the Network panel.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace DevtoolsNetwork {
/**
* Represents a network request for a document resource (script, image and so on). See HAR Specification for reference.
*/
interface Request {
/**
* Returns content of the response body.
*
* @returns A function that receives the response body when the request completes.
*/
getContent(): Promise<[string, string]>;
}
/**
* A HAR log. See HAR specification for details.
*/
interface GetHARCallbackHarLogType {
[s: string]: unknown;
}
interface Static {
/**
* Returns HAR log that contains all known network requests.
*
* @returns A function that receives the HAR log when the request completes.
*/
getHAR(): Promise<GetHARCallbackHarLogType>;
/**
* Fired when a network request is finished and all request data are available.
*
* @param request Description of a network request in the form of a HAR entry. See HAR specification for details.
*/
onRequestFinished: Events.Event<(request: Request) => void>;
/**
* Fired when the inspected window navigates to a new page.
*
* @param url URL of the new page.
*/
onNavigated: Events.Event<(url: string) => void>;
}
}

150
types/namespaces/devtools_panels.d.ts vendored Executable file
View File

@ -0,0 +1,150 @@
/**
* Namespace: browser.devtools.panels
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>chrome.devtools.panels</code> API to integrate your extension into Developer Tools window UI: create your
* own panels, access existing panels, and add sidebars.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
import { Manifest } from "./manifest";
export namespace DevtoolsPanels {
/**
* Represents the Elements panel.
*/
interface ElementsPanel {
/**
* Creates a pane within panel's sidebar.
*
* @param title Text that is displayed in sidebar caption.
* @returns A callback invoked when the sidebar is created.
*/
createSidebarPane(title: string): Promise<ExtensionSidebarPane>;
/**
* Fired when an object is selected in the panel.
*/
onSelectionChanged: Events.Event<() => void>;
}
/**
* Represents the Sources panel.
*/
interface SourcesPanel {
[s: string]: unknown;
}
/**
* Represents a panel created by extension.
*/
interface ExtensionPanel {
/**
* Fired when the user switches to the panel.
*
* @param window The JavaScript <code>window</code> object of panel's page.
*/
onShown: Events.Event<(window: Window) => void>;
/**
* Fired when the user switches away from the panel.
*/
onHidden: Events.Event<() => void>;
}
/**
* A sidebar created by the extension.
*/
interface ExtensionSidebarPane {
/**
* Sets an expression that is evaluated within the inspected page. The result is displayed in the sidebar pane.
*
* @param expression An expression to be evaluated in context of the inspected page. JavaScript objects and DOM nodes are
* displayed in an expandable tree similar to the console/watch.
* @param rootTitle Optional. An optional title for the root of the expression tree.
* @returns A callback invoked after the sidebar pane is updated with the expression evaluation results.
*/
setExpression(expression: string, rootTitle?: string): Promise<void>;
/**
* Sets a JSON-compliant object to be displayed in the sidebar pane.
*
* @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller
* (API client).
* @param rootTitle Optional. An optional title for the root of the expression tree.
* @returns A callback invoked after the sidebar is updated with the object.
*/
setObject(jsonObject: string | unknown[] | Record<string, unknown>, rootTitle?: string): Promise<void>;
/**
* Sets an HTML page to be displayed in the sidebar pane.
*
* @param path Relative path of an extension page to display within the sidebar.
*/
setPage(path: Manifest.ExtensionURL): void;
/**
* Fired when the sidebar pane becomes visible as a result of user switching to the panel that hosts it.
*
* @param window The JavaScript <code>window</code> object of the sidebar page, if one was set with the <code>setPage()
* </code> method.
*/
onShown: Events.Event<(window: Window) => void>;
/**
* Fired when the sidebar pane becomes hidden as a result of the user switching away from the panel that hosts the sidebar
* pane.
*/
onHidden: Events.Event<() => void>;
}
/**
* A button created by the extension.
*/
interface Button {
[s: string]: unknown;
}
interface Static {
/**
* Creates an extension panel.
*
* @param title Title that is displayed next to the extension icon in the Developer Tools toolbar.
* @param iconPath Path of the panel's icon relative to the extension directory, or an empty string to use the default
* extension icon as the panel icon.
* @param pagePath Path of the panel's HTML page relative to the extension directory.
* @returns A function that is called when the panel is created.
*/
create(
title: string,
iconPath: "" | Manifest.ExtensionURL,
pagePath: Manifest.ExtensionURL
): Promise<ExtensionPanel>;
/**
* Fired when the devtools theme changes.
*
* @param themeName The name of the current devtools theme.
*/
onThemeChanged: Events.Event<(themeName: string) => void>;
/**
* Elements panel.
*/
elements: ElementsPanel;
/**
* Sources panel.
*/
sources: SourcesPanel;
/**
* The name of the current devtools theme.
*/
themeName: string;
}
}

51
types/namespaces/dns.d.ts vendored Executable file
View File

@ -0,0 +1,51 @@
/**
* Namespace: browser.dns
* Generated from Mozilla sources. Do not manually edit!
*
* Asynchronous DNS API
* Permissions: "dns"
*/
export namespace Dns {
/**
* An object encapsulating a DNS Record.
*/
interface DNSRecord {
/**
* The canonical hostname for this record. this value is empty if the record was not fetched with the 'canonical_name'
* flag.
* Optional.
*/
canonicalName?: string;
/**
* Record retreived with TRR.
*/
isTRR: string;
addresses: string[];
}
type ResolveFlags = ResolveFlagsItemEnum[];
type ResolveFlagsItemEnum =
| "allow_name_collisions"
| "bypass_cache"
| "canonical_name"
| "disable_ipv4"
| "disable_ipv6"
| "disable_trr"
| "offline"
| "priority_low"
| "priority_medium"
| "speculate";
interface Static {
/**
* Resolves a hostname to a DNS record.
*
* @param hostname
* @param flags Optional.
*/
resolve(hostname: string, flags?: ResolveFlags): Promise<DNSRecord>;
}
}

658
types/namespaces/downloads.d.ts vendored Executable file
View File

@ -0,0 +1,658 @@
/**
* Namespace: browser.downloads
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "downloads"
*/
import { ExtensionTypes } from "./extensionTypes";
import { Events } from "./events";
export namespace Downloads {
type FilenameConflictAction = "uniquify" | "overwrite" | "prompt";
type InterruptReason =
| "FILE_FAILED"
| "FILE_ACCESS_DENIED"
| "FILE_NO_SPACE"
| "FILE_NAME_TOO_LONG"
| "FILE_TOO_LARGE"
| "FILE_VIRUS_INFECTED"
| "FILE_TRANSIENT_ERROR"
| "FILE_BLOCKED"
| "FILE_SECURITY_CHECK_FAILED"
| "FILE_TOO_SHORT"
| "NETWORK_FAILED"
| "NETWORK_TIMEOUT"
| "NETWORK_DISCONNECTED"
| "NETWORK_SERVER_DOWN"
| "NETWORK_INVALID_REQUEST"
| "SERVER_FAILED"
| "SERVER_NO_RANGE"
| "SERVER_BAD_CONTENT"
| "SERVER_UNAUTHORIZED"
| "SERVER_CERT_PROBLEM"
| "SERVER_FORBIDDEN"
| "USER_CANCELED"
| "USER_SHUTDOWN"
| "CRASH";
/**
* <dl><dt>file</dt><dd>The download's filename is suspicious.</dd><dt>url</dt><dd>The download's URL is known to be
* malicious.</dd><dt>content</dt><dd>The downloaded file is known to be malicious.</dd><dt>uncommon</dt><dd>
* The download's URL is not commonly downloaded and could be dangerous.</dd><dt>safe</dt><dd>
* The download presents no known danger to the user's computer.</dd></dl>These string constants will never change,
* however the set of DangerTypes may change.
*/
type DangerType = "file" | "url" | "content" | "uncommon" | "host" | "unwanted" | "safe" | "accepted";
/**
* <dl><dt>in_progress</dt><dd>The download is currently receiving data from the server.</dd><dt>interrupted</dt><dd>
* An error broke the connection with the file host.</dd><dt>complete</dt><dd>The download completed successfully.</dd></dl>
* These string constants will never change, however the set of States may change.
*/
type State = "in_progress" | "interrupted" | "complete";
interface DownloadItem {
/**
* An identifier that is persistent across browser sessions.
*/
id: number;
/**
* Absolute URL.
*/
url: string;
/**
* Optional.
*/
referrer?: string;
/**
* Absolute local path.
*/
filename: string;
/**
* False if this download is recorded in the history, true if it is not recorded.
*/
incognito: boolean;
/**
* The cookie store ID of the contextual identity.
* Optional.
*/
cookieStoreId?: string;
/**
* Indication of whether this download is thought to be safe or known to be suspicious.
*/
danger: DangerType;
/**
* The file's MIME type.
* Optional.
*/
mime?: string;
/**
* Number of milliseconds between the unix epoch and when this download began.
*/
startTime: string;
/**
* Number of milliseconds between the unix epoch and when this download ended.
* Optional.
*/
endTime?: string;
/**
* Optional.
*/
estimatedEndTime?: string;
/**
* Indicates whether the download is progressing, interrupted, or complete.
*/
state: State;
/**
* True if the download has stopped reading data from the host, but kept the connection open.
*/
paused: boolean;
canResume: boolean;
/**
* Number indicating why a download was interrupted.
* Optional.
*/
error?: InterruptReason;
/**
* Number of bytes received so far from the host, without considering file compression.
*/
bytesReceived: number;
/**
* Number of bytes in the whole file, without considering file compression, or -1 if unknown.
*/
totalBytes: number;
/**
* Number of bytes in the whole file post-decompression, or -1 if unknown.
*/
fileSize: number;
exists: boolean;
/**
* Optional.
*/
byExtensionId?: string;
/**
* Optional.
*/
byExtensionName?: string;
}
interface StringDelta {
/**
* Optional.
*/
current?: string;
/**
* Optional.
*/
previous?: string;
}
interface DoubleDelta {
/**
* Optional.
*/
current?: number;
/**
* Optional.
*/
previous?: number;
}
interface BooleanDelta {
/**
* Optional.
*/
current?: boolean;
/**
* Optional.
*/
previous?: boolean;
}
/**
* A time specified as a Date object, a number or string representing milliseconds since the epoch, or an ISO 8601 string
*/
type DownloadTime = string | ExtensionTypes.DateType;
/**
* Parameters that combine to specify a predicate that can be used to select a set of downloads.
* Used for example in search() and erase()
*/
interface DownloadQuery {
/**
* This array of search terms limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>filename</code>
* or <code>url</code> contain all of the search terms that do not begin with a dash '-' and none of the search terms that
* do begin with a dash.
* Optional.
*/
query?: string[];
/**
* Limits results to downloads that started before the given ms since the epoch.
* Optional.
*/
startedBefore?: DownloadTime;
/**
* Limits results to downloads that started after the given ms since the epoch.
* Optional.
*/
startedAfter?: DownloadTime;
/**
* Limits results to downloads that ended before the given ms since the epoch.
* Optional.
*/
endedBefore?: DownloadTime;
/**
* Limits results to downloads that ended after the given ms since the epoch.
* Optional.
*/
endedAfter?: DownloadTime;
/**
* Limits results to downloads whose totalBytes is greater than the given integer.
* Optional.
*/
totalBytesGreater?: number;
/**
* Limits results to downloads whose totalBytes is less than the given integer.
* Optional.
*/
totalBytesLess?: number;
/**
* Limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>filename</code>
* matches the given regular expression.
* Optional.
*/
filenameRegex?: string;
/**
* Limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>url</code>
* matches the given regular expression.
* Optional.
*/
urlRegex?: string;
/**
* Setting this integer limits the number of results. Otherwise, all matching <a href='#type-DownloadItem'>DownloadItems</a>
* will be returned.
* Optional.
*/
limit?: number;
/**
* Setting elements of this array to <a href='#type-DownloadItem'>DownloadItem</a> properties in order to sort the search
* results. For example, setting <code>orderBy='startTime'</code> sorts the <a href='#type-DownloadItem'>DownloadItems</a>
* by their start time in ascending order. To specify descending order, prefix <code>orderBy</code>
* with a hyphen: '-startTime'.
* Optional.
*/
orderBy?: string[];
/**
* Optional.
*/
id?: number;
/**
* Absolute URL.
* Optional.
*/
url?: string;
/**
* Absolute local path.
* Optional.
*/
filename?: string;
/**
* The cookie store ID of the contextual identity.
* Optional.
*/
cookieStoreId?: string;
/**
* Indication of whether this download is thought to be safe or known to be suspicious.
* Optional.
*/
danger?: DangerType;
/**
* The file's MIME type.
* Optional.
*/
mime?: string;
/**
* Optional.
*/
startTime?: string;
/**
* Optional.
*/
endTime?: string;
/**
* Indicates whether the download is progressing, interrupted, or complete.
* Optional.
*/
state?: State;
/**
* True if the download has stopped reading data from the host, but kept the connection open.
* Optional.
*/
paused?: boolean;
/**
* Why a download was interrupted.
* Optional.
*/
error?: InterruptReason;
/**
* Number of bytes received so far from the host, without considering file compression.
* Optional.
*/
bytesReceived?: number;
/**
* Number of bytes in the whole file, without considering file compression, or -1 if unknown.
* Optional.
*/
totalBytes?: number;
/**
* Number of bytes in the whole file post-decompression, or -1 if unknown.
* Optional.
*/
fileSize?: number;
/**
* Optional.
*/
exists?: boolean;
}
/**
* What to download and how.
*/
interface DownloadOptionsType {
/**
* The URL to download.
*/
url: string;
/**
* A file path relative to the Downloads directory to contain the downloaded file.
* Optional.
*/
filename?: string;
/**
* Whether to associate the download with a private browsing session.
* Optional.
*/
incognito?: boolean;
/**
* The cookie store ID of the contextual identity; requires "cookies" permission.
* Optional.
*/
cookieStoreId?: string;
/**
* Optional.
*/
conflictAction?: FilenameConflictAction;
/**
* Use a file-chooser to allow the user to select a filename. If the option is not specified,
* the file chooser will be shown only if the Firefox "Always ask you where to save files" option is enabled (i.e.
* the pref <code>browser.download.useDownloadDir</code> is set to <code>false</code>).
* Optional.
*/
saveAs?: boolean;
/**
* The HTTP method to use if the URL uses the HTTP[S] protocol.
* Optional.
*/
method?: DownloadOptionsTypeMethodEnum;
/**
* Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a
* dictionary containing the keys <code>name</code> and either <code>value</code> or <code>binaryValue</code>,
* restricted to those allowed by XMLHttpRequest.
* Optional.
*/
headers?: DownloadOptionsTypeHeadersItemType[];
/**
* Post body.
* Optional.
*/
body?: string;
/**
* When this flag is set to <code>true</code>, then the browser will allow downloads to proceed after encountering HTTP
* errors such as <code>404 Not Found</code>.
* Optional.
*/
allowHttpErrors?: boolean;
}
interface GetFileIconOptionsType {
/**
* The size of the icon. The returned icon will be square with dimensions size * size pixels.
* The default size for the icon is 32x32 pixels.
* Optional.
*/
size?: number;
}
interface OnChangedDownloadDeltaType {
/**
* The <code>id</code> of the <a href='#type-DownloadItem'>DownloadItem</a> that changed.
*/
id: number;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>url</code>.
* Optional.
*/
url?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>filename</code>.
* Optional.
*/
filename?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>danger</code>.
* Optional.
*/
danger?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>mime</code>.
* Optional.
*/
mime?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>startTime</code>.
* Optional.
*/
startTime?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>endTime</code>.
* Optional.
*/
endTime?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>state</code>.
* Optional.
*/
state?: StringDelta;
/**
* Optional.
*/
canResume?: BooleanDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>paused</code>.
* Optional.
*/
paused?: BooleanDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>error</code>.
* Optional.
*/
error?: StringDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>totalBytes</code>.
* Optional.
*/
totalBytes?: DoubleDelta;
/**
* Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>fileSize</code>.
* Optional.
*/
fileSize?: DoubleDelta;
/**
* Optional.
*/
exists?: BooleanDelta;
}
/**
* The HTTP method to use if the URL uses the HTTP[S] protocol.
*/
type DownloadOptionsTypeMethodEnum = "GET" | "POST";
interface DownloadOptionsTypeHeadersItemType {
/**
* Name of the HTTP header.
*/
name: string;
/**
* Value of the HTTP header.
*/
value: string;
}
interface Static {
/**
* Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set for its
* hostname. If both <code>filename</code> and <code>saveAs</code> are specified, then the Save As dialog will be displayed,
* pre-populated with the specified <code>filename</code>. If the download started successfully, <code>callback</code>
* will be called with the new <a href='#type-DownloadItem'>DownloadItem</a>'s <code>downloadId</code>.
* If there was an error starting the download, then <code>callback</code> will be called with <code>
* downloadId=undefined</code> and <a href='extension.html#property-lastError'>chrome.extension.lastError</a>
* will contain a descriptive string. The error strings are not guaranteed to remain backwards compatible between releases.
* You must not parse it.
*
* @param options What to download and how.
*/
download(options: DownloadOptionsType): Promise<number>;
/**
* Find <a href='#type-DownloadItem'>DownloadItems</a>. Set <code>query</code> to the empty object to get all <a
* href='#type-DownloadItem'>DownloadItems</a>. To get a specific <a href='#type-DownloadItem'>DownloadItem</a>,
* set only the <code>id</code> field.
*
* @param query
*/
search(query: DownloadQuery): Promise<DownloadItem[]>;
/**
* Pause the download. If the request was successful the download is in a paused state. Otherwise <a href='extension.
* html#property-lastError'>chrome.extension.lastError</a> contains an error message.
* The request will fail if the download is not active.
*
* @param downloadId The id of the download to pause.
*/
pause(downloadId: number): Promise<void>;
/**
* Resume a paused download. If the request was successful the download is in progress and unpaused.
* Otherwise <a href='extension.html#property-lastError'>chrome.extension.lastError</a> contains an error message.
* The request will fail if the download is not active.
*
* @param downloadId The id of the download to resume.
*/
resume(downloadId: number): Promise<void>;
/**
* Cancel a download. When <code>callback</code> is run, the download is cancelled, completed,
* interrupted or doesn't exist anymore.
*
* @param downloadId The id of the download to cancel.
*/
cancel(downloadId: number): Promise<void>;
/**
* Retrieve an icon for the specified download. For new downloads, file icons are available after the <a
* href='#event-onCreated'>onCreated</a> event has been received. The image returned by this function while a download is
* in progress may be different from the image returned after the download is complete.
* Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform.
* The icon that is returned will therefore depend on a number of factors including state of the download, platform,
* registered file types and visual theme. If a file icon cannot be determined, <a href='extension.
* html#property-lastError'>chrome.extension.lastError</a> will contain an error message.
*
* @param downloadId The identifier for the download.
* @param options Optional.
*/
getFileIcon(downloadId: number, options?: GetFileIconOptionsType): Promise<string>;
/**
* Open the downloaded file.
*
* @param downloadId
*/
open(downloadId: number): Promise<void>;
/**
* Show the downloaded file in its folder in a file manager.
*
* @param downloadId
*/
show(downloadId: number): Promise<boolean>;
showDefaultFolder(): void;
/**
* Erase matching <a href='#type-DownloadItem'>DownloadItems</a> from history
*
* @param query
*/
erase(query: DownloadQuery): Promise<number[]>;
/**
* @param downloadId
*/
removeFile(downloadId: number): Promise<void>;
/**
* This event fires with the <a href='#type-DownloadItem'>DownloadItem</a> object when a download begins.
*
* @param downloadItem
*/
onCreated: Events.Event<(downloadItem: DownloadItem) => void>;
/**
* Fires with the <code>downloadId</code> when a download is erased from history.
*
* @param downloadId The <code>id</code> of the <a href='#type-DownloadItem'>DownloadItem</a> that was erased.
*/
onErased: Events.Event<(downloadId: number) => void>;
/**
* When any of a <a href='#type-DownloadItem'>DownloadItem</a>'s properties except <code>bytesReceived</code> changes,
* this event fires with the <code>downloadId</code> and an object containing the properties that changed.
*
* @param downloadDelta
*/
onChanged: Events.Event<(downloadDelta: OnChangedDownloadDeltaType) => void>;
}
}

219
types/namespaces/events.d.ts vendored Executable file
View File

@ -0,0 +1,219 @@
/**
* Namespace: browser.events
* Generated from Mozilla sources. Do not manually edit!
*
* The <code>chrome.events</code> namespace contains common types used by APIs dispatching events to notify you when
* something interesting happens.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
export namespace Events {
/**
* Description of a declarative rule for handling events.
*/
interface Rule {
/**
* Optional identifier that allows referencing this rule.
* Optional.
*/
id?: string;
/**
* Tags can be used to annotate rules and perform operations on sets of rules.
* Optional.
*/
tags?: string[];
/**
* List of conditions that can trigger the actions.
*/
conditions: any[];
/**
* List of actions that are triggered if one of the condtions is fulfilled.
*/
actions: any[];
/**
* Optional priority of this rule. Defaults to 100.
* Optional.
*/
priority?: number;
}
/**
* An object which allows the addition and removal of listeners for a Chrome event.
*/
interface Event<T extends (...args: any[]) => any> {
/**
* Registers an event listener <em>callback</em> to an event.
*
* @param callback Called when an event occurs. The parameters of this function depend on the type of event.
* @param ...params Further parameters, depending on the event.
*/
addListener(callback: T, ...params: any[]): void;
/**
* Deregisters an event listener <em>callback</em> from an event.
*
* @param callback Listener that shall be unregistered.
*/
removeListener(callback: T): void;
/**
* @param callback Listener whose registration status shall be tested.
* @returns True if <em>callback</em> is registered to the event.
*/
hasListener(callback: T): boolean;
/**
* @returns True if any event listeners are registered to the event.
*/
hasListeners(): boolean;
}
/**
* Filters URLs for various criteria. See <a href='events#filtered'>event filtering</a>. All criteria are case sensitive.
*/
interface UrlFilter {
/**
* Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix
* 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the
* beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.')
* and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done
* separately using hostSuffix, because no implicit dot is added at the end of the host name.
* Optional.
*/
hostContains?: string;
/**
* Matches if the host name of the URL is equal to a specified string.
* Optional.
*/
hostEquals?: string;
/**
* Matches if the host name of the URL starts with a specified string.
* Optional.
*/
hostPrefix?: string;
/**
* Matches if the host name of the URL ends with a specified string.
* Optional.
*/
hostSuffix?: string;
/**
* Matches if the path segment of the URL contains a specified string.
* Optional.
*/
pathContains?: string;
/**
* Matches if the path segment of the URL is equal to a specified string.
* Optional.
*/
pathEquals?: string;
/**
* Matches if the path segment of the URL starts with a specified string.
* Optional.
*/
pathPrefix?: string;
/**
* Matches if the path segment of the URL ends with a specified string.
* Optional.
*/
pathSuffix?: string;
/**
* Matches if the query segment of the URL contains a specified string.
* Optional.
*/
queryContains?: string;
/**
* Matches if the query segment of the URL is equal to a specified string.
* Optional.
*/
queryEquals?: string;
/**
* Matches if the query segment of the URL starts with a specified string.
* Optional.
*/
queryPrefix?: string;
/**
* Matches if the query segment of the URL ends with a specified string.
* Optional.
*/
querySuffix?: string;
/**
* Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if
* they match the default port number.
* Optional.
*/
urlContains?: string;
/**
* Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL
* if they match the default port number.
* Optional.
*/
urlEquals?: string;
/**
* Matches if the URL (without fragment identifier) matches a specified regular expression.
* Port numbers are stripped from the URL if they match the default port number. The regular expressions use the <a
* href="https://github.com/google/re2/blob/master/doc/syntax.txt">RE2 syntax</a>.
* Optional.
*/
urlMatches?: string;
/**
* Matches if the URL without query segment and fragment identifier matches a specified regular expression.
* Port numbers are stripped from the URL if they match the default port number. The regular expressions use the <a
* href="https://github.com/google/re2/blob/master/doc/syntax.txt">RE2 syntax</a>.
* Optional.
*/
originAndPathMatches?: string;
/**
* Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL
* if they match the default port number.
* Optional.
*/
urlPrefix?: string;
/**
* Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if
* they match the default port number.
* Optional.
*/
urlSuffix?: string;
/**
* Matches if the scheme of the URL is equal to any of the schemes specified in the array.
* Optional.
*/
schemes?: string[];
/**
* Matches if the port of the URL is contained in any of the specified port lists. For example <code>[80, 443, [1000, 1200]]
* </code> matches all requests on port 80, 443 and in the range 1000-1200.
* Optional.
*/
ports?: Array<number | [number, number]>;
}
interface Static {
[s: string]: unknown;
}
}

64
types/namespaces/experiments.d.ts vendored Executable file
View File

@ -0,0 +1,64 @@
/**
* Namespace: browser.experiments
* Generated from Mozilla sources. Do not manually edit!
*/
export namespace Experiments {
interface ExperimentAPI {
schema: ExperimentURL;
/**
* Optional.
*/
parent?: ExperimentAPIParentType;
/**
* Optional.
*/
child?: ExperimentAPIChildType;
}
type ExperimentURL = string;
type APIPaths = APIPath[];
type APIPath = string[];
type APIEvents = APIEvent[];
type APIEvent = "startup";
type APIParentScope = "addon_parent" | "content_parent" | "devtools_parent";
type APIChildScope = "addon_child" | "content_child" | "devtools_child";
interface ExperimentAPIParentType {
/**
* Optional.
*/
events?: APIEvents;
/**
* Optional.
*/
paths?: APIPaths;
script: ExperimentURL;
/**
* Optional.
*/
scopes?: APIParentScope[];
}
interface ExperimentAPIChildType {
paths: APIPaths;
script: ExperimentURL;
scopes: APIChildScope[];
}
interface Static {
[s: string]: unknown;
}
}

75
types/namespaces/extension.d.ts vendored Executable file
View File

@ -0,0 +1,75 @@
/**
* Namespace: browser.extension
* Generated from Mozilla sources. Do not manually edit!
*
* The <code>browser.extension</code> API has utilities that can be used by any extension page.
* It includes support for exchanging messages between an extension and its content scripts or between extensions,
* as described in detail in $(topic:messaging)[Message Passing].
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
export namespace Extension {
/**
* The type of extension view.
*/
type ViewType = "tab" | "popup" | "sidebar";
interface GetViewsFetchPropertiesType {
/**
* The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab',
* 'popup', 'sidebar'.
* Optional.
*/
type?: ViewType;
/**
* The window to restrict the search to. If omitted, returns all views.
* Optional.
*/
windowId?: number;
/**
* Find a view according to a tab id. If this field is omitted, returns all views.
* Optional.
*/
tabId?: number;
}
interface Static {
/**
* Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension.
*
* @param fetchProperties Optional.
* @returns Array of global objects
*/
getViews(fetchProperties?: GetViewsFetchPropertiesType): Window[];
/**
* Returns the JavaScript 'window' object for the background page running inside the current extension.
* Returns null if the extension has no background page.
*/
getBackgroundPage(): Window;
/**
* Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in
* Incognito' checkbox.
*/
isAllowedIncognitoAccess(): Promise<boolean>;
/**
* Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow
* access to File URLs' checkbox.
*/
isAllowedFileSchemeAccess(): Promise<boolean>;
/**
* True for content scripts running inside incognito tabs, and for extension pages running inside an incognito process.
* The latter only applies to extensions with 'split' incognito_behavior.
* Optional.
*/
inIncognitoContext?: boolean;
}
}

154
types/namespaces/extensionTypes.d.ts vendored Executable file
View File

@ -0,0 +1,154 @@
/**
* Namespace: browser.extensionTypes
* Generated from Mozilla sources. Do not manually edit!
*
* The <code>browser.extensionTypes</code> API contains type declarations for WebExtensions.
*
* Comments found in source JSON schema files:
* Copyright 2014 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Manifest } from "./manifest";
export namespace ExtensionTypes {
/**
* The format of an image.
*/
type ImageFormat = "jpeg" | "png";
/**
* Details about the format, quality, area and scale of the capture.
*/
interface ImageDetails {
/**
* The format of the resulting image. Default is <code>"jpeg"</code>.
* Optional.
*/
format?: ImageFormat;
/**
* When format is <code>"jpeg"</code>, controls the quality of the resulting image. This value is ignored for PNG images.
* As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store
* it will decrease.
* Optional.
*/
quality?: number;
/**
* The area of the document to capture, in CSS pixels, relative to the page. If omitted, capture the visible viewport.
* Optional.
*/
rect?: ImageDetailsRectType;
/**
* The scale of the resulting image. Defaults to <code>devicePixelRatio</code>.
* Optional.
*/
scale?: number;
/**
* If true, temporarily resets the scroll position of the document to 0. Only takes effect if rect is also specified.
* Optional.
*/
resetScrollPosition?: boolean;
}
/**
* The soonest that the JavaScript or CSS will be injected into the tab.
*/
type RunAt = "document_start" | "document_end" | "document_idle";
/**
* The origin of the CSS to inject, this affects the cascading order (priority) of the stylesheet.
*/
type CSSOrigin = "user" | "author";
/**
* Details of the script or CSS to inject. Either the code or the file property must be set,
* but both may not be set at the same time.
*/
interface InjectDetails {
/**
* JavaScript or CSS code to inject.<br><br><b>Warning:</b><br>Be careful using the <code>code</code> parameter.
* Incorrect use of it may open your extension to <a href="https://en.wikipedia.org/wiki/Cross-site_scripting">
* cross site scripting</a> attacks.
* Optional.
*/
code?: string;
/**
* JavaScript or CSS file to inject.
* Optional.
*/
file?: string;
/**
* If allFrames is <code>true</code>, implies that the JavaScript or CSS should be injected into all frames of current page.
* By default, it's <code>false</code> and is only injected into the top frame.
* Optional.
*/
allFrames?: boolean;
/**
* If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has
* access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is <code>false</code>.
* Optional.
*/
matchAboutBlank?: boolean;
/**
* The ID of the frame to inject the script into. This may not be used in combination with <code>allFrames</code>.
* Optional.
*/
frameId?: number;
/**
* The soonest that the JavaScript or CSS will be injected into the tab. Defaults to "document_idle".
* Optional.
*/
runAt?: RunAt;
/**
* The css origin of the stylesheet to inject. Defaults to "author".
* Optional.
*/
cssOrigin?: CSSOrigin;
}
type DateType = string | number | Date;
type ExtensionFileOrCode = ExtensionFileOrCodeC1Type | ExtensionFileOrCodeC2Type;
/**
* A plain JSON value
*/
interface PlainJSONValue {
[s: string]: unknown;
}
/**
* The area of the document to capture, in CSS pixels, relative to the page. If omitted, capture the visible viewport.
*/
interface ImageDetailsRectType {
x: number;
y: number;
width: number;
height: number;
}
interface ExtensionFileOrCodeC1Type {
file: Manifest.ExtensionURL;
}
interface ExtensionFileOrCodeC2Type {
code: string;
}
interface Static {
[s: string]: unknown;
}
}

200
types/namespaces/find.d.ts vendored Executable file
View File

@ -0,0 +1,200 @@
/**
* Namespace: browser.find
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.find</code> API to interact with the browser's <code>Find</code> interface.
* Permissions: "find"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
export namespace Find {
interface RangeData {
/**
* The index of the frame containing the match. 0 corresponds to the parent window. Note that the order of objects in the
* rangeData array will sequentially line up with the order of frame indexes: for example,
* framePos for the first sequence of rangeData objects will be 0, framePos for the next sequence will be 1, and so on.
*/
framePos: number;
/**
* The ordinal position of the text node in which the match started.
*/
startTextNodePos: number;
/**
* The ordinal position of the text node in which the match ended.
*/
endTextNodePos: number;
/**
* The ordinal string position of the start of the matched word within start text node.
* If match word include in single text node, Extension can get match word between startOffset and endOffset string index
* in the single text node.
*/
startOffset: number;
/**
* The ordinal string position of the end of the matched word within end text node.
*/
endOffset: number;
}
interface Rectangle {
/**
* Pixels from the top.
*/
top: number;
/**
* Pixels from the left.
*/
left: number;
/**
* Pixels from the bottom.
*/
bottom: number;
/**
* Pixels from the right.
*/
right: number;
}
interface RectsAndTexts {
/**
* Rectangles relative to the top-left of the viewport.
*/
rectList: Rectangle[];
/**
* an array of strings, corresponding to the rectList array. The entry at textList[i]
* contains the part of the match bounded by the rectangle at rectList[i].
*/
textList: string[];
}
interface RectData {
/**
* The index of the frame containing the match. 0 corresponds to the parent window. Note that the order of objects in the
* rangeData array will sequentially line up with the order of frame indexes: for example,
* framePos for the first sequence of rangeData objects will be 0, framePos for the next sequence will be 1, and so on.
*/
rectsAndTexts: RectsAndTexts;
/**
* The complete text of the match.
*/
text: string;
}
interface FindResult {
/**
* The number of results found.
*/
count: number;
/**
* If includeRangeData was given in the options parameter, then this property will be included.
* It is provided as an array of RangeData objects, one for each match. Each RangeData object describes where in the DOM
* tree the match was found. This would enable, for example, an extension to get the text surrounding each match,
* so as to display context for the matches. The items correspond to the items given in rectData, so rangeData[i]
* describes the same match as rectData[i].
* Optional.
*/
rangeData?: RangeData[];
/**
* If includeRectData was given in the options parameter, then this property will be included.
* It is an array of RectData objects. It contains client rectangles for all the text matched in the search,
* relative to the top-left of the viewport. Extensions can use this to provide custom highlighting of the results.
* Optional.
*/
rectData?: RectData[];
}
/**
* Search parameters.
*/
interface FindParamsType {
/**
* Tab to query. Defaults to the active tab.
* Optional.
*/
tabId?: number;
/**
* Find only ranges with case sensitive match.
* Optional.
*/
caseSensitive?: boolean;
/**
* Find only ranges that match entire word.
* Optional.
*/
entireWord?: boolean;
/**
* Return rectangle data which describes visual position of search results.
* Optional.
*/
includeRectData?: boolean;
/**
* Return range data which provides range data in a serializable form.
* Optional.
*/
includeRangeData?: boolean;
}
/**
* highlightResults parameters
*/
interface HighlightResultsParamsType {
/**
* Found range to be highlighted. Default highlights all ranges.
* Optional.
*/
rangeIndex?: number;
/**
* Tab to highlight. Defaults to the active tab.
* Optional.
*/
tabId?: number;
/**
* Don't scroll to highlighted item.
* Optional.
*/
noScroll?: boolean;
}
interface Static {
/**
* Search for text in document and store found ranges in array, in document order.
*
* @param queryphrase The string to search for.
* @param params Optional. Search parameters.
*/
find(queryphrase: string, params?: FindParamsType): Promise<FindResult>;
/**
* Highlight a range
*
* @param params Optional. highlightResults parameters
*/
highlightResults(params?: HighlightResultsParamsType): Promise<void>;
/**
* Remove all highlighting from previous searches.
*
* @param tabId Optional. Tab to highlight. Defaults to the active tab.
*/
removeHighlighting(tabId?: number): Promise<void>;
}
}

134
types/namespaces/geckoProfiler.d.ts vendored Executable file
View File

@ -0,0 +1,134 @@
/**
* Namespace: browser.geckoProfiler
* Generated from Mozilla sources. Do not manually edit!
*
* Exposes the browser's profiler.
* Permissions: "geckoProfiler"
*/
import { Events } from "./events";
export namespace GeckoProfiler {
type ProfilerFeature =
| "java"
| "js"
| "leaf"
| "mainthreadio"
| "fileio"
| "fileioall"
| "noiostacks"
| "screenshots"
| "seqstyle"
| "stackwalk"
| "threads"
| "jstracer"
| "jsallocations"
| "nostacksampling"
| "preferencereads"
| "nativeallocations"
| "ipcmessages"
| "audiocallbacktracing"
| "cpu"
| "notimerresolutionchange"
| "cpuallthreads"
| "samplingallthreads"
| "markersallthreads"
| "responsiveness";
type supports = "windowLength";
interface StartSettingsType {
/**
* The maximum size in bytes of the buffer used to store profiling data. A larger value allows capturing a profile that
* covers a greater amount of time.
*/
bufferSize: number;
/**
* The length of the window of time that's kept in the buffer. Any collected samples are discarded as soon as they are
* older than the number of seconds specified in this setting. Zero means no duration restriction.
* Optional.
*/
windowLength?: number;
/**
* Interval in milliseconds between samples of profiling data. A smaller value will increase the detail of the profiles
* captured.
*/
interval: number;
/**
* A list of active features for the profiler.
*/
features: ProfilerFeature[];
/**
* A list of thread names for which to capture profiles.
* Optional.
*/
threads?: string[];
}
interface Static {
/**
* Starts the profiler with the specified settings.
*
* @param settings
*/
start(settings: StartSettingsType): void;
/**
* Stops the profiler and discards any captured profile data.
*/
stop(): void;
/**
* Pauses the profiler, keeping any profile data that is already written.
*/
pause(): void;
/**
* Resumes the profiler with the settings that were initially used to start it.
*/
resume(): void;
/**
* Gathers the profile data from the current profiling session, and writes it to disk.
* The returned promise resolves to a path that locates the created file.
*
* @param fileName The name of the file inside the profile/profiler directory
*/
dumpProfileToFile(fileName: string): void;
/**
* Gathers the profile data from the current profiling session.
*/
getProfile(): void;
/**
* Gathers the profile data from the current profiling session. The returned promise resolves to an array buffer that
* contains a JSON string.
*/
getProfileAsArrayBuffer(): void;
/**
* Gathers the profile data from the current profiling session. The returned promise resolves to an array buffer that
* contains a gzipped JSON string.
*/
getProfileAsGzippedArrayBuffer(): void;
/**
* Gets the debug symbols for a particular library.
*
* @param debugName The name of the library's debug file. For example, 'xul.pdb
* @param breakpadId The Breakpad ID of the library
*/
getSymbols(debugName: string, breakpadId: string): void;
/**
* Fires when the profiler starts/stops running.
*
* @param isRunning Whether the profiler is running or not. Pausing the profiler will not affect this value.
*/
onRunning: Events.Event<(isRunning: boolean) => void>;
}
}

268
types/namespaces/history.d.ts vendored Executable file
View File

@ -0,0 +1,268 @@
/**
* Namespace: browser.history
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.history</code> API to interact with the browser's record of visited pages. You can add, remove,
* and query for URLs in the browser's history. To override the history page with your own version, see $(topic:override)
* [Override Pages].
* Permissions: "history"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { ExtensionTypes } from "./extensionTypes";
import { Events } from "./events";
export namespace History {
/**
* The $(topic:transition-types)[transition type] for this visit from its referrer.
*/
type TransitionType =
| "link"
| "typed"
| "auto_bookmark"
| "auto_subframe"
| "manual_subframe"
| "generated"
| "auto_toplevel"
| "form_submit"
| "reload"
| "keyword"
| "keyword_generated";
/**
* An object encapsulating one result of a history query.
*/
interface HistoryItem {
/**
* The unique identifier for the item.
*/
id: string;
/**
* The URL navigated to by a user.
* Optional.
*/
url?: string;
/**
* The title of the page when it was last loaded.
* Optional.
*/
title?: string;
/**
* When this page was last loaded, represented in milliseconds since the epoch.
* Optional.
*/
lastVisitTime?: number;
/**
* The number of times the user has navigated to this page.
* Optional.
*/
visitCount?: number;
/**
* The number of times the user has navigated to this page by typing in the address.
* Optional.
*/
typedCount?: number;
}
/**
* An object encapsulating one visit to a URL.
*/
interface VisitItem {
/**
* The unique identifier for the item.
*/
id: string;
/**
* The unique identifier for this visit.
*/
visitId: string;
/**
* When this visit occurred, represented in milliseconds since the epoch.
* Optional.
*/
visitTime?: number;
/**
* The visit ID of the referrer.
*/
referringVisitId: string;
/**
* The $(topic:transition-types)[transition type] for this visit from its referrer.
*/
transition: TransitionType;
}
interface SearchQueryType {
/**
* A free-text query to the history service. Leave empty to retrieve all pages.
*/
text: string;
/**
* Limit results to those visited after this date. If not specified, this defaults to 24 hours in the past.
* Optional.
*/
startTime?: ExtensionTypes.DateType;
/**
* Limit results to those visited before this date.
* Optional.
*/
endTime?: ExtensionTypes.DateType;
/**
* The maximum number of results to retrieve. Defaults to 100.
* Optional.
*/
maxResults?: number;
}
interface GetVisitsDetailsType {
/**
* The URL for which to retrieve visit information. It must be in the format as returned from a call to history.search.
*/
url: string;
}
interface AddUrlDetailsType {
/**
* The URL to add. Must be a valid URL that can be added to history.
*/
url: string;
/**
* The title of the page.
* Optional.
*/
title?: string;
/**
* The $(topic:transition-types)[transition type] for this visit from its referrer.
* Optional.
*/
transition?: TransitionType;
/**
* The date when this visit occurred.
* Optional.
*/
visitTime?: ExtensionTypes.DateType;
}
interface DeleteUrlDetailsType {
/**
* The URL to remove.
*/
url: string;
}
interface DeleteRangeRangeType {
/**
* Items added to history after this date.
*/
startTime: ExtensionTypes.DateType;
/**
* Items added to history before this date.
*/
endTime: ExtensionTypes.DateType;
}
interface OnVisitRemovedRemovedType {
/**
* True if all history was removed. If true, then urls will be empty.
*/
allHistory: boolean;
urls: string[];
}
interface OnTitleChangedChangedType {
/**
* The URL for which the title has changed
*/
url: string;
/**
* The new title for the URL.
*/
title: string;
}
interface Static {
/**
* Searches the history for the last visit time of each page matching the query.
*
* @param query
*/
search(query: SearchQueryType): Promise<HistoryItem[]>;
/**
* Retrieves information about visits to a URL.
*
* @param details
*/
getVisits(details: GetVisitsDetailsType): Promise<VisitItem[]>;
/**
* Adds a URL to the history with a default visitTime of the current time and a default $(topic:transition-types)
* [transition type] of "link".
*
* @param details
*/
addUrl(details: AddUrlDetailsType): Promise<void>;
/**
* Removes all occurrences of the given URL from the history.
*
* @param details
*/
deleteUrl(details: DeleteUrlDetailsType): Promise<void>;
/**
* Removes all items within the specified date range from the history. Pages will not be removed from the history unless
* all visits fall within the range.
*
* @param range
*/
deleteRange(range: DeleteRangeRangeType): Promise<void>;
/**
* Deletes all items from the history.
*/
deleteAll(): Promise<void>;
/**
* Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded.
*
* @param result
*/
onVisited: Events.Event<(result: HistoryItem) => void>;
/**
* Fired when one or more URLs are removed from the history service. When all visits have been removed the URL is purged
* from history.
*
* @param removed
*/
onVisitRemoved: Events.Event<(removed: OnVisitRemovedRemovedType) => void>;
/**
* Fired when the title of a URL is changed in the browser history.
*
* @param changed
*/
onTitleChanged: Events.Event<(changed: OnTitleChangedChangedType) => void>;
}
}

82
types/namespaces/i18n.d.ts vendored Executable file
View File

@ -0,0 +1,82 @@
/**
* Namespace: browser.i18n
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.i18n</code> infrastructure to implement internationalization across your whole app or extension.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
export namespace I18n {
/**
* An ISO language code such as <code>en</code> or <code>fr</code>. For a complete list of languages supported by this
* method, see <a href='http://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc'>
* kLanguageInfoTable</a>. For an unknown language, <code>und</code> will be returned, which means that [percentage]
* of the text is unknown to CLD
*/
type LanguageCode = string;
/**
* LanguageDetectionResult object that holds detected langugae reliability and array of DetectedLanguage
*/
interface DetectLanguageCallbackResultType {
/**
* CLD detected language reliability
*/
isReliable: boolean;
/**
* array of detectedLanguage
*/
languages: DetectLanguageCallbackResultTypeLanguagesItemType[];
}
/**
* DetectedLanguage object that holds detected ISO language code and its percentage in the input string
*/
interface DetectLanguageCallbackResultTypeLanguagesItemType {
language: LanguageCode;
/**
* The percentage of the detected language
*/
percentage: number;
}
interface Static {
/**
* Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale,
* use $(ref:i18n.getUILanguage).
*/
getAcceptLanguages(): Promise<LanguageCode[]>;
/**
* Gets the localized string for the specified message. If the message is missing, this method returns an empty string ('').
* If the format of the <code>getMessage()</code> call is wrong &mdash; for example, <em>messageName</em>
* is not a string or the <em>substitutions</em> array has more than 9 elements &mdash; this method returns <code>
* undefined</code>.
*
* @param messageName The name of the message, as specified in the <code>$(topic:i18n-messages)[messages.json]</code> file.
* @param substitutions Optional. Substitution strings, if the message requires any.
* @returns Message localized for current locale.
*/
getMessage(messageName: string, substitutions?: any): string;
/**
* Gets the browser UI language of the browser. This is different from $(ref:i18n.getAcceptLanguages)
* which returns the preferred user languages.
*
* @returns The browser UI language code such as en-US or fr-FR.
*/
getUILanguage(): string;
/**
* Detects the language of the provided text using CLD.
*
* @param text User input string to be translated.
*/
detectLanguage(text: string): Promise<DetectLanguageCallbackResultType>;
}
}

45
types/namespaces/identity.d.ts vendored Executable file
View File

@ -0,0 +1,45 @@
/**
* Namespace: browser.identity
* Generated from Mozilla sources. Do not manually edit!
*
* Use the chrome.identity API to get OAuth2 access tokens.
* Permissions: "identity"
*/
import { Manifest } from "./manifest";
export namespace Identity {
/**
* An object encapsulating an OAuth account id.
*/
interface AccountInfo {
/**
* A unique identifier for the account. This ID will not change for the lifetime of the account.
*/
id: string;
}
interface LaunchWebAuthFlowDetailsType {
url: Manifest.HttpURL;
/**
* Optional.
*/
interactive?: boolean;
}
interface Static {
/**
* Starts an auth flow at the specified URL.
*
* @param details
*/
launchWebAuthFlow(details: LaunchWebAuthFlowDetailsType): Promise<string>;
/**
* Generates a redirect URL to be used in |launchWebAuthFlow|.
*
* @param path Optional. The path appended to the end of the generated URL.
*/
getRedirectURL(path?: string): string;
}
}

43
types/namespaces/idle.d.ts vendored Executable file
View File

@ -0,0 +1,43 @@
/**
* Namespace: browser.idle
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.idle</code> API to detect when the machine's idle state changes.
* Permissions: "idle"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Idle {
type IdleState = "active" | "idle" | "locked";
interface Static {
/**
* Returns "idle" if the user has not generated any input for a specified number of seconds, or "active" otherwise.
*
* @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since
* the last user input detected.
*/
queryState(detectionIntervalInSeconds: number): Promise<IdleState>;
/**
* Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events.
* The default interval is 60 seconds.
*
* @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state.
*/
setDetectionInterval(intervalInSeconds: number): void;
/**
* Fired when the system changes to an active or idle state. The event fires with "idle" if the the user has not generated
* any input for a specified number of seconds, and "active" when the user generates input on an idle system.
*
* @param newState
*/
onStateChanged: Events.Event<(newState: IdleState) => void>;
}
}

253
types/namespaces/management.d.ts vendored Executable file
View File

@ -0,0 +1,253 @@
/**
* Namespace: browser.management
* Generated from Mozilla sources. Do not manually edit!
*
* The <code>browser.management</code> API provides ways to manage the list of extensions that are installed and running.
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Manifest } from "./manifest";
import { Events } from "./events";
export namespace Management {
/**
* Information about an icon belonging to an extension.
*/
interface IconInfo {
/**
* A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24,
* and 16.
*/
size: number;
/**
* The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is disabled,
* for example), append <code>?grayscale=true</code> to the URL.
*/
url: string;
}
/**
* A reason the item is disabled.
*/
type ExtensionDisabledReason = "unknown" | "permissions_increase";
/**
* The type of this extension, 'extension' or 'theme'.
*/
type ExtensionType = "extension" | "theme";
/**
* How the extension was installed. One of<br><var>development</var>: The extension was loaded unpacked in developer mode,
* <br><var>normal</var>: The extension was installed normally via an .xpi file,<br><var>sideload</var>
* : The extension was installed by other software on the machine,<br><var>other</var>
* : The extension was installed by other means.
*/
type ExtensionInstallType = "development" | "normal" | "sideload" | "other";
/**
* Information about an installed extension.
*/
interface ExtensionInfo {
/**
* The extension's unique identifier.
*/
id: string;
/**
* The name of this extension.
*/
name: string;
/**
* A short version of the name of this extension.
* Optional.
*/
shortName?: string;
/**
* The description of this extension.
*/
description: string;
/**
* The <a href='manifest/version'>version</a> of this extension.
*/
version: string;
/**
* The <a href='manifest/version#version_name'>version name</a> of this extension if the manifest specified one.
* Optional.
*/
versionName?: string;
/**
* Whether this extension can be disabled or uninstalled by the user.
*/
mayDisable: boolean;
/**
* Whether it is currently enabled or disabled.
*/
enabled: boolean;
/**
* A reason the item is disabled.
* Optional.
*/
disabledReason?: ExtensionDisabledReason;
/**
* The type of this extension, 'extension' or 'theme'.
*/
type: ExtensionType;
/**
* The URL of the homepage of this extension.
* Optional.
*/
homepageUrl?: string;
/**
* The update URL of this extension.
* Optional.
*/
updateUrl?: string;
/**
* The url for the item's options page, if it has one.
*/
optionsUrl: string;
/**
* A list of icon information. Note that this just reflects what was declared in the manifest,
* and the actual image at that url may be larger or smaller than what was declared,
* so you might consider using explicit width and height attributes on img tags referencing these images.
* See the <a href='manifest/icons'>manifest documentation on icons</a> for more details.
* Optional.
*/
icons?: IconInfo[];
/**
* Returns a list of API based permissions.
* Optional.
*/
permissions?: string[];
/**
* Returns a list of host based permissions.
* Optional.
*/
hostPermissions?: string[];
/**
* How the extension was installed.
*/
installType: ExtensionInstallType;
}
interface InstallOptionsType {
/**
* URL pointing to the XPI file on addons.mozilla.org or similar.
*/
url: Manifest.HttpURL;
/**
* A hash of the XPI file, using sha256 or stronger.
* Optional.
*/
hash?: string;
}
interface InstallCallbackResultType {
id: Manifest.ExtensionID;
}
interface UninstallSelfOptionsType {
/**
* Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false.
* Optional.
*/
showConfirmDialog?: boolean;
/**
* The message to display to a user when being asked to confirm removal of the extension.
* Optional.
*/
dialogMessage?: string;
}
interface Static {
/**
* Returns a list of information about installed extensions.
*/
getAll(): Promise<ExtensionInfo[]>;
/**
* Returns information about the installed extension that has the given ID.
*
* @param id The ID from an item of $(ref:management.ExtensionInfo).
*/
get(id: Manifest.ExtensionID): Promise<ExtensionInfo>;
/**
* Installs and enables a theme extension from the given url.
*
* @param options
*/
install(options: InstallOptionsType): Promise<InstallCallbackResultType>;
/**
* Returns information about the calling extension. Note: This function can be used without requesting the 'management'
* permission in the manifest.
*/
getSelf(): Promise<ExtensionInfo>;
/**
* Uninstalls the calling extension. Note: This function can be used without requesting the 'management' permission in the
* manifest.
*
* @param options Optional.
*/
uninstallSelf(options?: UninstallSelfOptionsType): Promise<void>;
/**
* Enables or disables the given add-on.
*
* @param id ID of the add-on to enable/disable.
* @param enabled Whether to enable or disable the add-on.
*/
setEnabled(id: string, enabled: boolean): Promise<void>;
/**
* Fired when an addon has been disabled.
*
* @param info
*/
onDisabled: Events.Event<(info: ExtensionInfo) => void>;
/**
* Fired when an addon has been enabled.
*
* @param info
*/
onEnabled: Events.Event<(info: ExtensionInfo) => void>;
/**
* Fired when an addon has been installed.
*
* @param info
*/
onInstalled: Events.Event<(info: ExtensionInfo) => void>;
/**
* Fired when an addon has been uninstalled.
*
* @param info
*/
onUninstalled: Events.Event<(info: ExtensionInfo) => void>;
}
}

1202
types/namespaces/manifest.d.ts vendored Executable file

File diff suppressed because it is too large Load Diff

515
types/namespaces/menus.d.ts vendored Executable file
View File

@ -0,0 +1,515 @@
/**
* Namespace: browser.menus
* Generated from Mozilla sources. Do not manually edit!
*
* Use the browser.menus API to add items to the browser's menus. You can choose what types of objects your context menu
* additions apply to, such as images, hyperlinks, and pages.
* Permissions: "menus"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Extension } from "./extension";
import { Tabs } from "./tabs";
import { Events } from "./events";
export namespace Menus {
/**
* The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts
* except for 'tab' and 'tools_menu'.
*/
type ContextType =
| "all"
| "page"
| "frame"
| "selection"
| "link"
| "editable"
| "password"
| "image"
| "video"
| "audio"
| "launcher"
| "bookmark"
| "tab"
| "tools_menu"
| "browser_action"
| "page_action"
| "action";
/**
* The type of menu item.
*/
type ItemType = "normal" | "checkbox" | "radio" | "separator";
/**
* Information sent when a context menu item is clicked.
*/
interface OnClickData {
/**
* The ID of the menu item that was clicked.
*/
menuItemId: number | string;
/**
* The parent ID, if any, for the item clicked.
* Optional.
*/
parentMenuItemId?: number | string;
/**
* The type of view where the menu is clicked. May be unset if the menu is not associated with a view.
* Optional.
*/
viewType?: Extension.ViewType;
/**
* One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements.
* Optional.
*/
mediaType?: string;
/**
* If the element is a link, the text of that link.
* Optional.
*/
linkText?: string;
/**
* If the element is a link, the URL it points to.
* Optional.
*/
linkUrl?: string;
/**
* Will be present for elements with a 'src' URL.
* Optional.
*/
srcUrl?: string;
/**
* The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where
* there is no current page, such as in a launcher context menu.
* Optional.
*/
pageUrl?: string;
/**
* The id of the frame of the element where the context menu was clicked.
* Optional.
*/
frameId?: number;
/**
* The URL of the frame of the element where the context menu was clicked, if it was in a frame.
* Optional.
*/
frameUrl?: string;
/**
* The text for the context selection, if any.
* Optional.
*/
selectionText?: string;
/**
* A flag indicating whether the element is editable (text input, textarea, etc.).
*/
editable: boolean;
/**
* A flag indicating the state of a checkbox or radio item before it was clicked.
* Optional.
*/
wasChecked?: boolean;
/**
* A flag indicating the state of a checkbox or radio item after it is clicked.
* Optional.
*/
checked?: boolean;
/**
* The id of the bookmark where the context menu was clicked, if it was on a bookmark.
*/
bookmarkId: string;
/**
* An array of keyboard modifiers that were held while the menu item was clicked.
*/
modifiers: OnClickDataModifiersItemEnum[];
/**
* An integer value of button by which menu item was clicked.
* Optional.
*/
button?: number;
/**
* An identifier of the clicked element, if any. Use menus.getTargetElement in the page to find the corresponding element.
* Optional.
*/
targetElementId?: number;
}
interface CreateCreatePropertiesType {
/**
* The type of menu item. Defaults to 'normal' if not specified.
* Optional.
*/
type?: ItemType;
/**
* The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.
* Optional.
*/
id?: string;
/**
* Optional.
*/
icons?: Record<string, string>;
/**
* The text to be displayed in the item; this is <em>required</em> unless <code>type</code> is 'separator'.
* When the context is 'selection', you can use <code>%s</code> within the string to show the selected text. For example,
* if this parameter's value is "Translate '%s' to Pig Latin" and the user selects the word "cool",
* the context menu item for the selection is "Translate 'cool' to Pig Latin".
* Optional.
*/
title?: string;
/**
* The initial state of a checkbox or radio item: true for selected and false for unselected.
* Only one radio item can be selected at a time in a given group of radio items.
* Optional.
*/
checked?: boolean;
/**
* List of contexts this menu item will appear in. Defaults to ['page'] if not specified.
* Optional.
*/
contexts?: ContextType[];
/**
* List of view types where the menu item will be shown. Defaults to any view, including those without a viewType.
* Optional.
*/
viewTypes?: Extension.ViewType[];
/**
* Whether the item is visible in the menu.
* Optional.
*/
visible?: boolean;
/**
* A function that will be called back when the menu item is clicked. Event pages cannot use this; instead,
* they should register a listener for $(ref:contextMenus.onClicked).
*
* @param info Information about the item clicked and the context where the click happened.
* @param tab The details of the tab where the click took place. Note: this parameter only present for extensions.
*/
onclick?(info: OnClickData, tab: Tabs.Tab): void;
/**
* The ID of a parent menu item; this makes the item a child of a previously added item.
* Optional.
*/
parentId?: number | string;
/**
* Lets you restrict the item to apply only to documents whose URL matches one of the given patterns.
* (This applies to frames as well.) For details on the format of a pattern, see $(topic:match_patterns)[Match Patterns].
* Optional.
*/
documentUrlPatterns?: string[];
/**
* Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of
* anchor tags.
* Optional.
*/
targetUrlPatterns?: string[];
/**
* Whether this context menu item is enabled or disabled. Defaults to true.
* Optional.
*/
enabled?: boolean;
/**
* Specifies a command to issue for the context click.
* Optional.
*/
command?:
| string
| "_execute_browser_action"
| "_execute_page_action"
| "_execute_sidebar_action"
| "_execute_action"
| "_execute_page_action"
| "_execute_sidebar_action";
}
/**
* The properties to update. Accepts the same values as the create function.
*/
interface UpdateUpdatePropertiesType {
/**
* Optional.
*/
type?: ItemType;
/**
* Optional.
*/
icons?: Record<string, string>;
/**
* Optional.
*/
title?: string;
/**
* Optional.
*/
checked?: boolean;
/**
* Optional.
*/
contexts?: ContextType[];
/**
* Optional.
*/
viewTypes?: Extension.ViewType[];
/**
* Whether the item is visible in the menu.
* Optional.
*/
visible?: boolean;
/**
* @param info
* @param tab The details of the tab where the click took place. Note: this parameter only present for extensions.
*/
onclick?(info: OnClickData, tab: Tabs.Tab): void;
/**
* Note: You cannot change an item to be a child of one of its own descendants.
* Optional.
*/
parentId?: number | string;
/**
* Optional.
*/
documentUrlPatterns?: string[];
/**
* Optional.
*/
targetUrlPatterns?: string[];
/**
* Optional.
*/
enabled?: boolean;
}
interface OverrideContextContextOptionsType {
/**
* Whether to also include default menu items in the menu.
* Optional.
*/
showDefaults?: boolean;
/**
* ContextType to override, to allow menu items from other extensions in the menu. Currently only 'bookmark' and 'tab' are
* supported. showDefaults cannot be used with this option.
* Optional.
*/
context?: OverrideContextContextOptionsTypeContextEnum;
/**
* Required when context is 'bookmark'. Requires 'bookmark' permission.
* Optional.
*/
bookmarkId?: string;
/**
* Required when context is 'tab'. Requires 'tabs' permission.
* Optional.
*/
tabId?: number;
}
/**
* Information about the context of the menu action and the created menu items. For more information about each property,
* see OnClickData. The following properties are only set if the extension has host permissions for the given context:
* linkUrl, linkText, srcUrl, pageUrl, frameUrl, selectionText.
*/
interface OnShownInfoType {
/**
* A list of IDs of the menu items that were shown.
*/
menuIds: Array<number | string>;
/**
* A list of all contexts that apply to the menu.
*/
contexts: ContextType[];
/**
* Optional.
*/
viewType?: Extension.ViewType;
editable: boolean;
/**
* Optional.
*/
mediaType?: string;
/**
* Optional.
*/
linkUrl?: string;
/**
* Optional.
*/
linkText?: string;
/**
* Optional.
*/
srcUrl?: string;
/**
* Optional.
*/
pageUrl?: string;
/**
* Optional.
*/
frameUrl?: string;
/**
* Optional.
*/
selectionText?: string;
/**
* Optional.
*/
targetElementId?: number;
}
type OnClickDataModifiersItemEnum = "Shift" | "Alt" | "Command" | "Ctrl" | "MacCtrl";
/**
* ContextType to override, to allow menu items from other extensions in the menu. Currently only 'bookmark' and 'tab' are
* supported. showDefaults cannot be used with this option.
*/
type OverrideContextContextOptionsTypeContextEnum = "bookmark" | "tab";
interface Static {
/**
* Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation
* callback fires (the details will be in $(ref:runtime.lastError)).
*
* @param createProperties
* @param callback Optional. Called when the item has been created in the browser. If there were any problems creating the
* item, details will be available in $(ref:runtime.lastError).
* @returns The ID of the newly created item.
*/
create(createProperties: CreateCreatePropertiesType, callback?: () => void): number | string;
/**
* Updates a previously created context menu item.
*
* @param id The ID of the item to update.
* @param updateProperties The properties to update. Accepts the same values as the create function.
* @returns Called when the context menu has been updated.
*/
update(id: number | string, updateProperties: UpdateUpdatePropertiesType): Promise<void>;
/**
* Removes a context menu item.
*
* @param menuItemId The ID of the context menu item to remove.
* @returns Called when the context menu has been removed.
*/
remove(menuItemId: number | string): Promise<void>;
/**
* Removes all context menu items added by this extension.
*
* @returns Called when removal is complete.
*/
removeAll(): Promise<void>;
/**
* Show the matching menu items from this extension instead of the default menu. This should be called during a
* 'contextmenu' DOM event handler, and only applies to the menu that opens after this event.
*
* @param contextOptions
*/
overrideContext(contextOptions: OverrideContextContextOptionsType): void;
/**
* Updates the extension items in the shown menu, including changes that have been made since the menu was shown.
* Has no effect if the menu is hidden. Rebuilding a shown menu is an expensive operation,
* only invoke this method when necessary.
*/
refresh(): Promise<void>;
/**
* Retrieve the element that was associated with a recent contextmenu event.
*
* @param targetElementId The identifier of the clicked element, available as info.targetElementId in the menus.onShown,
* onClicked or onclick event.
*/
getTargetElement(targetElementId: number): Element;
/**
* Fired when a context menu item is clicked.
*
* @param info Information about the item clicked and the context where the click happened.
* @param tab Optional. The details of the tab where the click took place. If the click did not take place in a tab,
* this parameter will be missing.
*/
onClicked: Events.Event<(info: OnClickData, tab: Tabs.Tab | undefined) => void>;
/**
* Fired when a menu is shown. The extension can add, modify or remove menu items and call menus.refresh()
* to update the menu.
*
* @param info Information about the context of the menu action and the created menu items.
* For more information about each property, see OnClickData. The following properties are only set if the extension has
* host permissions for the given context: linkUrl, linkText, srcUrl, pageUrl, frameUrl, selectionText.
* @param tab The details of the tab where the menu was opened.
*/
onShown: Events.Event<(info: OnShownInfoType, tab: Tabs.Tab) => void>;
/**
* Fired when a menu is hidden. This event is only fired if onShown has fired before.
*/
onHidden: Events.Event<() => void>;
/**
* The maximum number of top level extension items that can be added to an extension action context menu.
* Any items beyond this limit will be ignored.
*/
ACTION_MENU_TOP_LEVEL_LIMIT: 6;
}
}

53
types/namespaces/networkStatus.d.ts vendored Executable file
View File

@ -0,0 +1,53 @@
/**
* Namespace: browser.networkStatus
* Generated from Mozilla sources. Do not manually edit!
*
* This API provides the ability to determine the status of and detect changes in the network connection.
* This API can only be used in privileged extensions.
* Permissions: "networkStatus"
*/
import { Events } from "./events";
export namespace NetworkStatus {
interface NetworkLinkInfo {
/**
* Status of the network link, if "unknown" then link is usually assumed to be "up"
*/
status: NetworkLinkInfoStatusEnum;
/**
* If known, the type of network connection that is avialable.
*/
type: NetworkLinkInfoTypeEnum;
/**
* If known, the network id or name.
* Optional.
*/
id?: string;
}
/**
* Status of the network link, if "unknown" then link is usually assumed to be "up"
*/
type NetworkLinkInfoStatusEnum = "unknown" | "up" | "down";
/**
* If known, the type of network connection that is avialable.
*/
type NetworkLinkInfoTypeEnum = "unknown" | "ethernet" | "usb" | "wifi" | "wimax" | "mobile";
interface Static {
/**
* Returns the $(ref:NetworkLinkInfo} of the current network connection.
*/
getLinkInfo(): void;
/**
* Fired when the network connection state changes.
*
* @param details
*/
onConnectionChanged: Events.Event<(details: NetworkLinkInfo) => void>;
}
}

109
types/namespaces/normandyAddonStudy.d.ts vendored Executable file
View File

@ -0,0 +1,109 @@
/**
* Namespace: browser.normandyAddonStudy
* Generated from Mozilla sources. Do not manually edit!
*
* Normandy Study API
* Permissions: "normandyAddonStudy"
*/
import { ExtensionTypes } from "./extensionTypes";
import { Events } from "./events";
export namespace NormandyAddonStudy {
interface Study {
/**
* The ID of the recipe for the study.
*/
recipeId: number;
/**
* A slug to identify the study.
*/
slug: string;
/**
* The name presented on about:studies.
*/
userFacingName: string;
/**
* The description presented on about:studies.
*/
userFacingDescription: string;
/**
* The study branch in which the user is enrolled.
*/
branch: string;
/**
* The state of the study.
*/
active: boolean;
/**
* The ID of the extension installed by the study.
*/
addonId: string;
/**
* The URL of the XPI that was downloaded and installed by the study.
*/
addonUrl: string;
/**
* The version of the extension installed by the study.
*/
addonVersion: string;
/**
* The start date for the study.
*/
studyStartDate: ExtensionTypes.DateType;
/**
* The end date for the study.
*/
studyEndDate: ExtensionTypes.DateType;
/**
* The record ID for the extension in Normandy server's database.
*/
extensionApiId: number;
/**
* A hash of the extension XPI file.
*/
extensionHash: string;
/**
* The algorithm used to hash the extension XPI file.
*/
extensionHashAlgorithm: string;
}
interface Static {
/**
* Returns a study object for the current study.
*/
getStudy(): void;
/**
* Marks the study as ended and then uninstalls the addon.
*
* @param reason The reason why the study is ending.
*/
endStudy(reason: string): void;
/**
* Returns an object with metadata about the client which may be required for constructing survey URLs.
*/
getClientMetadata(): void;
/**
* Fired when a user unenrolls from a study but before the addon is uninstalled.
*
* @param reason The reason why the study is ending.
*/
onUnenroll: Events.Event<(reason: string) => void>;
}
}

236
types/namespaces/notifications.d.ts vendored Executable file
View File

@ -0,0 +1,236 @@
/**
* Namespace: browser.notifications
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "notifications"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Notifications {
type TemplateType = "basic" | "image" | "list" | "progress";
type PermissionLevel = "granted" | "denied";
interface NotificationItem {
/**
* Title of one item of a list notification.
*/
title: string;
/**
* Additional details about this item.
*/
message: string;
}
interface CreateNotificationOptions {
/**
* Which type of notification to display.
*/
type: TemplateType;
/**
* A URL to the sender's avatar, app icon, or a thumbnail for image notifications.
* Optional.
*/
iconUrl?: string;
/**
* A URL to the app icon mask.
* Optional.
*/
appIconMaskUrl?: string;
/**
* Title of the notification (e.g. sender name for email).
*/
title: string;
/**
* Main notification content.
*/
message: string;
/**
* Alternate notification content with a lower-weight font.
* Optional.
*/
contextMessage?: string;
/**
* Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.
* Optional.
*/
priority?: number;
/**
* A timestamp associated with the notification, in milliseconds past the epoch.
* Optional.
*/
eventTime?: number;
/**
* A URL to the image thumbnail for image-type notifications.
* Optional.
*/
imageUrl?: string;
/**
* Items for multi-item notifications.
* Optional.
*/
items?: NotificationItem[];
/**
* Current progress ranges from 0 to 100.
* Optional.
*/
progress?: number;
/**
* Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.
* Optional.
*/
isClickable?: boolean;
}
interface UpdateNotificationOptions {
/**
* Which type of notification to display.
* Optional.
*/
type?: TemplateType;
/**
* A URL to the sender's avatar, app icon, or a thumbnail for image notifications.
* Optional.
*/
iconUrl?: string;
/**
* A URL to the app icon mask.
* Optional.
*/
appIconMaskUrl?: string;
/**
* Title of the notification (e.g. sender name for email).
* Optional.
*/
title?: string;
/**
* Main notification content.
* Optional.
*/
message?: string;
/**
* Alternate notification content with a lower-weight font.
* Optional.
*/
contextMessage?: string;
/**
* Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.
* Optional.
*/
priority?: number;
/**
* A timestamp associated with the notification, in milliseconds past the epoch.
* Optional.
*/
eventTime?: number;
/**
* A URL to the image thumbnail for image-type notifications.
* Optional.
*/
imageUrl?: string;
/**
* Items for multi-item notifications.
* Optional.
*/
items?: NotificationItem[];
/**
* Current progress ranges from 0 to 100.
* Optional.
*/
progress?: number;
/**
* Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.
* Optional.
*/
isClickable?: boolean;
}
interface Static {
/**
* Creates and displays a notification.
*
* @param notificationId Optional. Identifier of the notification. If it is empty, this method generates an id.
* If it matches an existing notification, this method first clears that notification before proceeding with the create
* operation.
* @param options Contents of the notification.
*/
create(notificationId: string | undefined, options: CreateNotificationOptions): Promise<string>;
/**
* Creates and displays a notification.
*
* @param options Contents of the notification.
*/
create(options: CreateNotificationOptions): Promise<string>;
/**
* Clears an existing notification.
*
* @param notificationId The id of the notification to be updated.
*/
clear(notificationId: string): Promise<boolean>;
/**
* Retrieves all the notifications.
*/
getAll(): Promise<Record<string, CreateNotificationOptions>>;
/**
* Fired when the notification closed, either by the system or by user action.
*
* @param notificationId The notificationId of the closed notification.
* @param byUser True if the notification was closed by the user.
*/
onClosed: Events.Event<(notificationId: string, byUser: boolean) => void>;
/**
* Fired when the user clicked in a non-button area of the notification.
*
* @param notificationId The notificationId of the clicked notification.
*/
onClicked: Events.Event<(notificationId: string) => void>;
/**
* Fired when the user pressed a button in the notification.
*
* @param notificationId The notificationId of the clicked notification.
* @param buttonIndex The index of the button clicked by the user.
*/
onButtonClicked: Events.Event<(notificationId: string, buttonIndex: number) => void>;
/**
* Fired when the notification is shown.
*
* @param notificationId The notificationId of the shown notification.
*/
onShown: Events.Event<(notificationId: string) => void>;
}
}

92
types/namespaces/omnibox.d.ts vendored Executable file
View File

@ -0,0 +1,92 @@
/**
* Namespace: browser.omnibox
* Generated from Mozilla sources. Do not manually edit!
*
* The omnibox API allows you to register a keyword with Firefox's address bar.
* Permissions: "manifest:omnibox"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Events } from "./events";
export namespace Omnibox {
/**
* The style type.
*/
type DescriptionStyleType = "url" | "match" | "dim";
/**
* The window disposition for the omnibox query. This is the recommended context to display results. For example,
* if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation should
* take place in a new selected tab.
*/
type OnInputEnteredDisposition = "currentTab" | "newForegroundTab" | "newBackgroundTab";
/**
* A suggest result.
*/
interface SuggestResult {
/**
* The text that is put into the URL bar, and that is sent to the extension when the user chooses this entry.
*/
content: string;
/**
* The text that is displayed in the URL dropdown. Can contain XML-style markup for styling.
* The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query),
* and 'dim' (for dim helper text). The styles can be nested, eg. <dim><match>dimmed match</match></dim>.
* You must escape the five predefined entities to display them as text: stackoverflow.com/a/1091953/89484
*/
description: string;
}
/**
* A suggest result.
*/
interface DefaultSuggestResult {
/**
* The text that is displayed in the URL dropdown.
*/
description: string;
}
interface Static {
/**
* Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the
* first suggestion row underneath the URL bar.
*
* @param suggestion A partial SuggestResult object, without the 'content' parameter.
*/
setDefaultSuggestion(suggestion: DefaultSuggestResult): void;
/**
* User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once
* per input session, and before any onInputChanged events.
*/
onInputStarted: Events.Event<() => void>;
/**
* User has changed what is typed into the omnibox.
*
* @param text
* @param suggest A callback passed to the onInputChanged event used for sending suggestions back to the browser.
*/
onInputChanged: Events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void>;
/**
* User has accepted what is typed into the omnibox.
*
* @param text
* @param disposition
*/
onInputEntered: Events.Event<(text: string, disposition: OnInputEnteredDisposition) => void>;
/**
* User has ended the keyword input session without accepting the input.
*/
onInputCancelled: Events.Event<() => void>;
}
}

188
types/namespaces/pageAction.d.ts vendored Executable file
View File

@ -0,0 +1,188 @@
/**
* Namespace: browser.pageAction
* Generated from Mozilla sources. Do not manually edit!
*
* Use the <code>browser.pageAction</code> API to put icons inside the address bar. Page actions represent actions that can
* be taken on the current page, but that aren't applicable to all pages.
* Permissions: "manifest:page_action"
*
* Comments found in source JSON schema files:
* Copyright (c) 2012 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
import { Tabs } from "./tabs";
import { Events } from "./events";
export namespace PageAction {
/**
* Pixel data for an image. Must be an ImageData object (for example, from a <code>canvas</code> element).
*/
interface ImageDataType extends ImageData {
[s: string]: unknown;
}
/**
* Information sent when a page action is clicked.
*/
interface OnClickData {
/**
* An array of keyboard modifiers that were held while the menu item was clicked.
*/
modifiers: OnClickDataModifiersItemEnum[];
/**
* An integer value of button by which menu item was clicked.
* Optional.
*/
button?: number;
}
interface IsShownDetailsType {
/**
* Specify the tab to get the shownness from.
*/
tabId: number;
}
interface SetTitleDetailsType {
/**
* The id of the tab for which you want to modify the page action.
*/
tabId: number;
/**
* The tooltip string.
*/
title: string | null;
}
interface GetTitleDetailsType {
/**
* Specify the tab to get the title from.
*/
tabId: number;
}
interface SetIconDetailsType {
/**
* The id of the tab for which you want to modify the page action.
*/
tabId: number;
/**
* Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set.
* If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density.
* If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>
* scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported.
* At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.
* imageData = {'19': foo}'
* Optional.
*/
imageData?: ImageDataType | Record<string, ImageDataType>;
/**
* Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set.
* If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density.
* If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>
* scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported.
* At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}'
* Optional.
*/
path?: string | Record<string, string>;
}
interface SetPopupDetailsType {
/**
* The id of the tab for which you want to modify the page action.
*/
tabId: number;
/**
* The html file to show in a popup. If set to the empty string (''), no popup is shown.
*/
popup: string | null;
}
interface GetPopupDetailsType {
/**
* Specify the tab to get the popup from.
*/
tabId: number;
}
type OnClickDataModifiersItemEnum = "Shift" | "Alt" | "Command" | "Ctrl" | "MacCtrl";
interface Static {
/**
* Shows the page action. The page action is shown whenever the tab is selected.
*
* @param tabId The id of the tab for which you want to modify the page action.
*/
show(tabId: number): Promise<void>;
/**
* Hides the page action.
*
* @param tabId The id of the tab for which you want to modify the page action.
*/
hide(tabId: number): Promise<void>;
/**
* Checks whether the page action is shown.
*
* @param details
*/
isShown(details: IsShownDetailsType): Promise<boolean>;
/**
* Sets the title of the page action. This is displayed in a tooltip over the page action.
*
* @param details
*/
setTitle(details: SetTitleDetailsType): void;
/**
* Gets the title of the page action.
*
* @param details
*/
getTitle(details: GetTitleDetailsType): Promise<string>;
/**
* Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data
* from a canvas element, or as dictionary of either one of those. Either the <b>path</b> or the <b>imageData</b>
* property must be specified.
*
* @param details
*/
setIcon(details: SetIconDetailsType): Promise<void>;
/**
* Sets the html document to be opened as a popup when the user clicks on the page action's icon.
*
* @param details
*/
setPopup(details: SetPopupDetailsType): Promise<void>;
/**
* Gets the html document set as the popup for this page action.
*
* @param details
*/
getPopup(details: GetPopupDetailsType): Promise<string>;
/**
* Opens the extension page action in the active window.
*/
openPopup(): Promise<void>;
/**
* Fired when a page action icon is clicked. This event will not fire if the page action has a popup.
*
* @param tab
* @param info Optional.
*/
onClicked: Events.Event<(tab: Tabs.Tab, info: OnClickData | undefined) => void>;
}
}

76
types/namespaces/permissions.d.ts vendored Executable file
View File

@ -0,0 +1,76 @@
/**
* Namespace: browser.permissions
* Generated from Mozilla sources. Do not manually edit!
*
* Permissions: "manifest:optional_permissions"
*/
import { Manifest } from "./manifest";
import { Events } from "./events";
export namespace Permissions {
interface Permissions {
/**
* Optional.
*/
permissions?: Manifest.OptionalPermission[];
/**
* Optional.
*/
origins?: Manifest.MatchPattern[];
}
interface AnyPermissions {
/**
* Optional.
*/
permissions?: Manifest.Permission[];
/**
* Optional.
*/
origins?: Manifest.MatchPattern[];
}
interface Static {
/**
* Get a list of all the extension's permissions.
*/
getAll(): Promise<AnyPermissions>;
/**
* Check if the extension has the given permissions.
*
* @param permissions
*/
contains(permissions: AnyPermissions): Promise<boolean>;
/**
* Request the given permissions.
*
* @param permissions
*/
request(permissions: Permissions): Promise<boolean>;
/**
* Relinquish the given permissions.
*
* @param permissions
*/
remove(permissions: Permissions): Promise<boolean>;
/**
* Fired when the extension acquires new permissions.
*
* @param permissions
*/
onAdded: Events.Event<(permissions: Permissions) => void>;
/**
* Fired when permissions are removed from the extension.
*
* @param permissions
*/
onRemoved: Events.Event<(permissions: Permissions) => void>;
}
}

Some files were not shown because too many files have changed in this diff Show More