summaryrefslogtreecommitdiffstats
path: root/toolkit/components/webextensions
diff options
context:
space:
mode:
authorMatt A. Tobin <email@mattatobin.com>2018-02-10 02:51:36 -0500
committerMatt A. Tobin <email@mattatobin.com>2018-02-10 02:51:36 -0500
commit37d5300335d81cecbecc99812747a657588c63eb (patch)
tree765efa3b6a56bb715d9813a8697473e120436278 /toolkit/components/webextensions
parentb2bdac20c02b12f2057b9ef70b0a946113a00e00 (diff)
parent4fb11cd5966461bccc3ed1599b808237be6b0de9 (diff)
downloadUXP-37d5300335d81cecbecc99812747a657588c63eb.tar
UXP-37d5300335d81cecbecc99812747a657588c63eb.tar.gz
UXP-37d5300335d81cecbecc99812747a657588c63eb.tar.lz
UXP-37d5300335d81cecbecc99812747a657588c63eb.tar.xz
UXP-37d5300335d81cecbecc99812747a657588c63eb.zip
Merge branch 'ext-work'
Diffstat (limited to 'toolkit/components/webextensions')
-rw-r--r--toolkit/components/webextensions/.eslintrc.js497
-rw-r--r--toolkit/components/webextensions/Extension.jsm902
-rw-r--r--toolkit/components/webextensions/ExtensionAPI.jsm81
-rw-r--r--toolkit/components/webextensions/ExtensionChild.jsm1040
-rw-r--r--toolkit/components/webextensions/ExtensionCommon.jsm680
-rw-r--r--toolkit/components/webextensions/ExtensionContent.jsm1048
-rw-r--r--toolkit/components/webextensions/ExtensionManagement.jsm321
-rw-r--r--toolkit/components/webextensions/ExtensionParent.jsm551
-rw-r--r--toolkit/components/webextensions/ExtensionStorage.jsm241
-rw-r--r--toolkit/components/webextensions/ExtensionTestCommon.jsm343
-rw-r--r--toolkit/components/webextensions/ExtensionUtils.jsm1215
-rw-r--r--toolkit/components/webextensions/ExtensionXPCShellUtils.jsm306
-rw-r--r--toolkit/components/webextensions/LegacyExtensionsUtils.jsm250
-rw-r--r--toolkit/components/webextensions/MessageChannel.jsm797
-rw-r--r--toolkit/components/webextensions/NativeMessaging.jsm443
-rw-r--r--toolkit/components/webextensions/Schemas.jsm2143
-rw-r--r--toolkit/components/webextensions/ext-alarms.js155
-rw-r--r--toolkit/components/webextensions/ext-backgroundPage.js147
-rw-r--r--toolkit/components/webextensions/ext-browser-content.js217
-rw-r--r--toolkit/components/webextensions/ext-c-backgroundPage.js45
-rw-r--r--toolkit/components/webextensions/ext-c-extension.js57
-rw-r--r--toolkit/components/webextensions/ext-c-runtime.js93
-rw-r--r--toolkit/components/webextensions/ext-c-storage.js62
-rw-r--r--toolkit/components/webextensions/ext-c-test.js188
-rw-r--r--toolkit/components/webextensions/ext-cookies.js484
-rw-r--r--toolkit/components/webextensions/ext-downloads.js799
-rw-r--r--toolkit/components/webextensions/ext-extension.js20
-rw-r--r--toolkit/components/webextensions/ext-i18n.js34
-rw-r--r--toolkit/components/webextensions/ext-idle.js94
-rw-r--r--toolkit/components/webextensions/ext-management.js109
-rw-r--r--toolkit/components/webextensions/ext-notifications.js161
-rw-r--r--toolkit/components/webextensions/ext-runtime.js134
-rw-r--r--toolkit/components/webextensions/ext-storage.js46
-rw-r--r--toolkit/components/webextensions/ext-topSites.js24
-rw-r--r--toolkit/components/webextensions/ext-webNavigation.js192
-rw-r--r--toolkit/components/webextensions/ext-webRequest.js115
-rw-r--r--toolkit/components/webextensions/extensions-toolkit.manifest49
-rw-r--r--toolkit/components/webextensions/jar.mn26
-rw-r--r--toolkit/components/webextensions/moz.build41
-rw-r--r--toolkit/components/webextensions/schemas/LICENSE27
-rw-r--r--toolkit/components/webextensions/schemas/alarms.json145
-rw-r--r--toolkit/components/webextensions/schemas/cookies.json224
-rw-r--r--toolkit/components/webextensions/schemas/downloads.json793
-rw-r--r--toolkit/components/webextensions/schemas/events.json322
-rw-r--r--toolkit/components/webextensions/schemas/experiments.json16
-rw-r--r--toolkit/components/webextensions/schemas/extension.json178
-rw-r--r--toolkit/components/webextensions/schemas/extension_types.json83
-rw-r--r--toolkit/components/webextensions/schemas/i18n.json132
-rw-r--r--toolkit/components/webextensions/schemas/idle.json70
-rw-r--r--toolkit/components/webextensions/schemas/jar.mn25
-rw-r--r--toolkit/components/webextensions/schemas/management.json250
-rw-r--r--toolkit/components/webextensions/schemas/manifest.json377
-rw-r--r--toolkit/components/webextensions/schemas/moz.build7
-rw-r--r--toolkit/components/webextensions/schemas/native_host_manifest.json37
-rw-r--r--toolkit/components/webextensions/schemas/notifications.json416
-rw-r--r--toolkit/components/webextensions/schemas/runtime.json592
-rw-r--r--toolkit/components/webextensions/schemas/storage.json229
-rw-r--r--toolkit/components/webextensions/schemas/test.json215
-rw-r--r--toolkit/components/webextensions/schemas/top_sites.json66
-rw-r--r--toolkit/components/webextensions/schemas/web_navigation.json387
-rw-r--r--toolkit/components/webextensions/schemas/web_request.json616
-rw-r--r--toolkit/components/webextensions/test/mochitest/.eslintrc.js35
-rw-r--r--toolkit/components/webextensions/test/mochitest/chrome.ini35
-rw-r--r--toolkit/components/webextensions/test/mochitest/chrome_head.js12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html7
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html9
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html11
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_csp.html14
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_csp.html^headers^1
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_image_bad.pngbin0 -> 5401 bytes
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_image_good.pngbin0 -> 580 bytes
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_image_redirect.pngbin0 -> 5401 bytes
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_mixed.html13
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_permission_xhr.html55
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html13
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_sample.html12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_script_bad.js3
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_script_good.js3
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_script_redirect.js4
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_script_xhr.js5
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_style_bad.css3
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_style_good.css3
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_style_redirect.css3
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_teardown_test.js24
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html9
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html8
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^1
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html12
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html8
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html7
-rw-r--r--toolkit/components/webextensions/test/mochitest/file_with_about_blank.html10
-rw-r--r--toolkit/components/webextensions/test/mochitest/head.js13
-rw-r--r--toolkit/components/webextensions/test/mochitest/head_cookies.js167
-rw-r--r--toolkit/components/webextensions/test/mochitest/head_webrequest.js331
-rw-r--r--toolkit/components/webextensions/test/mochitest/mochitest.ini114
-rw-r--r--toolkit/components/webextensions/test/mochitest/redirection.sjs4
-rw-r--r--toolkit/components/webextensions/test/mochitest/return_headers.sjs20
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html166
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html84
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html80
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html68
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html106
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html141
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html64
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html50
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html164
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html53
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html83
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html96
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html61
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_clipboard.html140
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js158
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html46
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html47
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html47
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html76
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html162
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html116
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html117
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html88
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html54
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html81
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html165
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html48
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html81
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html95
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html89
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html59
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html96
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_cookies.html234
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html93
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html72
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html112
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html86
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html92
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_generate.html49
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_geturl.html72
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_i18n.html432
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html116
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html49
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html86
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html63
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_notifications.html224
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html119
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html83
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html103
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html127
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html78
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html61
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html60
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_schema.html73
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html101
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html83
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html79
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html93
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html330
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html118
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html202
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html150
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_test.html191
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html170
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html353
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html559
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html308
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html116
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html327
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html216
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html199
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html105
-rw-r--r--toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html86
-rw-r--r--toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js8
-rw-r--r--toolkit/components/webextensions/test/mochitest/webrequest_test.jsm22
-rw-r--r--toolkit/components/webextensions/test/mochitest/webrequest_worker.js3
-rw-r--r--toolkit/components/webextensions/test/xpcshell/.eslintrc.js9
-rw-r--r--toolkit/components/webextensions/test/xpcshell/data/file_download.html12
-rw-r--r--toolkit/components/webextensions/test/xpcshell/data/file_download.txt1
-rw-r--r--toolkit/components/webextensions/test/xpcshell/head.js111
-rw-r--r--toolkit/components/webextensions/test/xpcshell/head_native_messaging.js131
-rw-r--r--toolkit/components/webextensions/test/xpcshell/head_sync.js67
-rw-r--r--toolkit/components/webextensions/test/xpcshell/native_messaging.ini13
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js38
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_csp_validator.js85
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js210
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js33
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js44
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js44
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js64
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js91
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js23
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js24
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js22
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js40
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js72
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js45
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js34
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js190
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js76
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js354
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js862
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js402
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js175
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_extension.js55
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_idle.js202
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js37
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js168
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js188
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js50
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_management.js20
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js135
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js30
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js27
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js13
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js514
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js128
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js82
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js30
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js23
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js26
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js25
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js337
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js79
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js59
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js54
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js51
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js1427
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js147
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js102
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js232
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_simple.js69
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_storage.js334
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js85
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js55
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_locale_converter.js133
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_locale_data.js130
-rw-r--r--toolkit/components/webextensions/test/xpcshell/test_native_messaging.js302
-rw-r--r--toolkit/components/webextensions/test/xpcshell/xpcshell.ini69
240 files changed, 38348 insertions, 0 deletions
diff --git a/toolkit/components/webextensions/.eslintrc.js b/toolkit/components/webextensions/.eslintrc.js
new file mode 100644
index 000000000..70196fc6a
--- /dev/null
+++ b/toolkit/components/webextensions/.eslintrc.js
@@ -0,0 +1,497 @@
+"use strict";
+
+module.exports = { // eslint-disable-line no-undef
+ "extends": "../../.eslintrc.js",
+
+ "parserOptions": {
+ "ecmaVersion": 8,
+ },
+
+ "globals": {
+ "Cc": true,
+ "Ci": true,
+ "Components": true,
+ "Cr": true,
+ "Cu": true,
+ "dump": true,
+ "TextDecoder": false,
+ "TextEncoder": false,
+ // Specific to WebExtensions:
+ "Extension": true,
+ "ExtensionManagement": true,
+ "extensions": true,
+ "global": true,
+ "NetUtil": true,
+ "openOptionsPage": true,
+ "require": false,
+ "runSafe": true,
+ "runSafeSync": true,
+ "runSafeSyncWithoutClone": true,
+ "Services": true,
+ "TabManager": true,
+ "WindowListManager": true,
+ "XPCOMUtils": true,
+ },
+
+ "rules": {
+ // Rules from the mozilla plugin
+ "mozilla/balanced-listeners": "error",
+ "mozilla/no-aArgs": "error",
+ "mozilla/no-cpows-in-tests": "warn",
+ "mozilla/var-only-at-top-level": "warn",
+
+ "valid-jsdoc": ["error", {
+ "prefer": {
+ "return": "returns",
+ },
+ "preferType": {
+ "Boolean": "boolean",
+ "Number": "number",
+ "String": "string",
+ "bool": "boolean",
+ },
+ "requireParamDescription": false,
+ "requireReturn": false,
+ "requireReturnDescription": false,
+ }],
+
+ // Braces only needed for multi-line arrow function blocks
+ // "arrow-body-style": ["error", "as-needed"],
+
+ // Require spacing around =>
+ "arrow-spacing": "error",
+
+ // Always require spacing around a single line block
+ "block-spacing": "warn",
+
+ // Forbid spaces inside the square brackets of array literals.
+ "array-bracket-spacing": ["error", "never"],
+
+ // Forbid spaces inside the curly brackets of object literals.
+ "object-curly-spacing": ["error", "never"],
+
+ // No space padding in parentheses
+ "space-in-parens": ["error", "never"],
+
+ // Enforce one true brace style (opening brace on the same line) and avoid
+ // start and end braces on the same line.
+ "brace-style": ["error", "1tbs", {"allowSingleLine": true}],
+
+ // No space before always a space after a comma
+ "comma-spacing": ["error", {"before": false, "after": true}],
+
+ // Commas at the end of the line not the start
+ "comma-style": "error",
+
+ // Don't require spaces around computed properties
+ "computed-property-spacing": ["error", "never"],
+
+ // Functions are not required to consistently return something or nothing
+ "consistent-return": "off",
+
+ // Require braces around blocks that start a new line
+ "curly": ["error", "all"],
+
+ // Always require a trailing EOL
+ "eol-last": "error",
+
+ // Require function* name()
+ "generator-star-spacing": ["error", {"before": false, "after": true}],
+
+ // Two space indent
+ "indent": ["error", 2, {"SwitchCase": 1}],
+
+ // Space after colon not before in property declarations
+ "key-spacing": ["error", {"beforeColon": false, "afterColon": true, "mode": "minimum"}],
+
+ // Require spaces before and after finally, catch, etc.
+ "keyword-spacing": "error",
+
+ // Unix linebreaks
+ "linebreak-style": ["error", "unix"],
+
+ // Always require parenthesis for new calls
+ "new-parens": "error",
+
+ // Use [] instead of Array()
+ "no-array-constructor": "error",
+
+ // No duplicate arguments in function declarations
+ "no-dupe-args": "error",
+
+ // No duplicate keys in object declarations
+ "no-dupe-keys": "error",
+
+ // No duplicate cases in switch statements
+ "no-duplicate-case": "error",
+
+ // If an if block ends with a return no need for an else block
+ // "no-else-return": "error",
+
+ // Disallow empty statements. This will report an error for:
+ // try { something(); } catch (e) {}
+ // but will not report it for:
+ // try { something(); } catch (e) { /* Silencing the error because ...*/ }
+ // which is a valid use case.
+ "no-empty": "error",
+
+ // No empty character classes in regex
+ "no-empty-character-class": "error",
+
+ // Disallow empty destructuring
+ "no-empty-pattern": "error",
+
+ // No assiging to exception variable
+ "no-ex-assign": "error",
+
+ // No using !! where casting to boolean is already happening
+ "no-extra-boolean-cast": "warn",
+
+ // No double semicolon
+ "no-extra-semi": "error",
+
+ // No overwriting defined functions
+ "no-func-assign": "error",
+
+ // No invalid regular expresions
+ "no-invalid-regexp": "error",
+
+ // No odd whitespace characters
+ "no-irregular-whitespace": "error",
+
+ // No single if block inside an else block
+ "no-lonely-if": "warn",
+
+ // No mixing spaces and tabs in indent
+ "no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
+
+ // Disallow use of multiple spaces (sometimes used to align const values,
+ // array or object items, etc.). It's hard to maintain and doesn't add that
+ // much benefit.
+ "no-multi-spaces": "warn",
+
+ // No reassigning native JS objects
+ "no-native-reassign": "error",
+
+ // No (!foo in bar)
+ "no-negated-in-lhs": "error",
+
+ // Nested ternary statements are confusing
+ "no-nested-ternary": "error",
+
+ // Use {} instead of new Object()
+ "no-new-object": "error",
+
+ // No Math() or JSON()
+ "no-obj-calls": "error",
+
+ // No octal literals
+ "no-octal": "error",
+
+ // No redeclaring variables
+ "no-redeclare": "error",
+
+ // No unnecessary comparisons
+ "no-self-compare": "error",
+
+ // No spaces between function name and parentheses
+ "no-spaced-func": "warn",
+
+ // No trailing whitespace
+ "no-trailing-spaces": "error",
+
+ // Error on newline where a semicolon is needed
+ "no-unexpected-multiline": "error",
+
+ // No unreachable statements
+ "no-unreachable": "error",
+
+ // No expressions where a statement is expected
+ "no-unused-expressions": "error",
+
+ // No declaring variables that are never used
+ "no-unused-vars": ["error", {"args": "none", "varsIgnorePattern": "^(Cc|Ci|Cr|Cu|EXPORTED_SYMBOLS)$"}],
+
+ // No using variables before defined
+ "no-use-before-define": "error",
+
+ // No using with
+ "no-with": "error",
+
+ // Always require semicolon at end of statement
+ "semi": ["error", "always"],
+
+ // Require space before blocks
+ "space-before-blocks": "error",
+
+ // Never use spaces before function parentheses
+ "space-before-function-paren": ["error", {"anonymous": "never", "named": "never"}],
+
+ // Require spaces around operators, except for a|0.
+ "space-infix-ops": ["error", {"int32Hint": true}],
+
+ // ++ and -- should not need spacing
+ "space-unary-ops": ["warn", {"nonwords": false, "words": true, "overrides": {"typeof": false}}],
+
+ // No comparisons to NaN
+ "use-isnan": "error",
+
+ // Only check typeof against valid results
+ "valid-typeof": "error",
+
+ // Disallow using variables outside the blocks they are defined (especially
+ // since only let and const are used, see "no-var").
+ "block-scoped-var": "error",
+
+ // Allow trailing commas for easy list extension. Having them does not
+ // impair readability, but also not required either.
+ "comma-dangle": ["error", "always-multiline"],
+
+ // Warn about cyclomatic complexity in functions.
+ "complexity": "warn",
+
+ // Don't warn for inconsistent naming when capturing this (not so important
+ // with auto-binding fat arrow functions).
+ // "consistent-this": ["error", "self"],
+
+ // Don't require a default case in switch statements. Avoid being forced to
+ // add a bogus default when you know all possible cases are handled.
+ "default-case": "off",
+
+ // Enforce dots on the next line with property name.
+ "dot-location": ["error", "property"],
+
+ // Encourage the use of dot notation whenever possible.
+ "dot-notation": "error",
+
+ // Allow using == instead of ===, in the interest of landing something since
+ // the devtools codebase is split on convention here.
+ "eqeqeq": "off",
+
+ // Don't require function expressions to have a name.
+ // This makes the code more verbose and hard to read. Our engine already
+ // does a fantastic job assigning a name to the function, which includes
+ // the enclosing function name, and worst case you have a line number that
+ // you can just look up.
+ "func-names": "off",
+
+ // Allow use of function declarations and expressions.
+ "func-style": "off",
+
+ // Don't enforce the maximum depth that blocks can be nested. The complexity
+ // rule is a better rule to check this.
+ "max-depth": "off",
+
+ // Maximum length of a line.
+ // Disabled because we exceed this in too many places.
+ "max-len": [0, 80],
+
+ // Maximum depth callbacks can be nested.
+ "max-nested-callbacks": ["error", 4],
+
+ // Don't limit the number of parameters that can be used in a function.
+ "max-params": "off",
+
+ // Don't limit the maximum number of statement allowed in a function. We
+ // already have the complexity rule that's a better measurement.
+ "max-statements": "off",
+
+ // Don't require a capital letter for constructors, only check if all new
+ // operators are followed by a capital letter. Don't warn when capitalized
+ // functions are used without the new operator.
+ "new-cap": ["off", {"capIsNew": false}],
+
+ // Allow use of bitwise operators.
+ "no-bitwise": "off",
+
+ // Disallow use of arguments.caller or arguments.callee.
+ "no-caller": "error",
+
+ // Disallow the catch clause parameter name being the same as a variable in
+ // the outer scope, to avoid confusion.
+ "no-catch-shadow": "off",
+
+ // Disallow assignment in conditional expressions.
+ "no-cond-assign": "error",
+
+ // Disallow using the console API.
+ "no-console": "error",
+
+ // Allow using constant expressions in conditions like while (true)
+ "no-constant-condition": "off",
+
+ // Allow use of the continue statement.
+ "no-continue": "off",
+
+ // Disallow control characters in regular expressions.
+ "no-control-regex": "error",
+
+ // Disallow use of debugger.
+ "no-debugger": "error",
+
+ // Disallow deletion of variables (deleting properties is fine).
+ "no-delete-var": "error",
+
+ // Allow division operators explicitly at beginning of regular expression.
+ "no-div-regex": "off",
+
+ // Disallow use of eval(). We have other APIs to evaluate code in content.
+ "no-eval": "error",
+
+ // Disallow adding to native types
+ "no-extend-native": "error",
+
+ // Disallow unnecessary function binding.
+ "no-extra-bind": "error",
+
+ // Allow unnecessary parentheses, as they may make the code more readable.
+ "no-extra-parens": "off",
+
+ // Disallow fallthrough of case statements, except if there is a comment.
+ "no-fallthrough": "error",
+
+ // Allow the use of leading or trailing decimal points in numeric literals.
+ "no-floating-decimal": "off",
+
+ // Allow comments inline after code.
+ "no-inline-comments": "off",
+
+ // Disallow use of labels for anything other then loops and switches.
+ "no-labels": ["error", {"allowLoop": true}],
+
+ // Disallow use of multiline strings (use template strings instead).
+ "no-multi-str": "warn",
+
+ // Disallow multiple empty lines.
+ "no-multiple-empty-lines": [1, {"max": 2}],
+
+ // Allow reassignment of function parameters.
+ "no-param-reassign": "off",
+
+ // Allow string concatenation with __dirname and __filename (not a node env).
+ "no-path-concat": "off",
+
+ // Allow use of unary operators, ++ and --.
+ "no-plusplus": "off",
+
+ // Allow using process.env (not a node environment).
+ "no-process-env": "off",
+
+ // Allow using process.exit (not a node environment).
+ "no-process-exit": "off",
+
+ // Disallow usage of __proto__ property.
+ "no-proto": "error",
+
+ // Disallow multiple spaces in a regular expression literal.
+ "no-regex-spaces": "error",
+
+ // Allow reserved words being used as object literal keys.
+ "no-reserved-keys": "off",
+
+ // Don't restrict usage of specified node modules (not a node environment).
+ "no-restricted-modules": "off",
+
+ // Disallow use of assignment in return statement. It is preferable for a
+ // single line of code to have only one easily predictable effect.
+ "no-return-assign": "error",
+
+ // Don't warn about declaration of variables already declared in the outer scope.
+ "no-shadow": "off",
+
+ // Disallow shadowing of names such as arguments.
+ "no-shadow-restricted-names": "error",
+
+ // Allow use of synchronous methods (not a node environment).
+ "no-sync": "off",
+
+ // Allow the use of ternary operators.
+ "no-ternary": "off",
+
+ // Disallow throwing literals (eg. throw "error" instead of
+ // throw new Error("error")).
+ "no-throw-literal": "error",
+
+ // Disallow use of undeclared variables unless mentioned in a /* global */
+ // block. Note that globals from head.js are automatically imported in tests
+ // by the import-headjs-globals rule form the mozilla eslint plugin.
+ "no-undef": "error",
+
+ // Allow dangling underscores in identifiers (for privates).
+ "no-underscore-dangle": "off",
+
+ // Allow use of undefined variable.
+ "no-undefined": "off",
+
+ // Disallow the use of Boolean literals in conditional expressions.
+ "no-unneeded-ternary": "error",
+
+ // We use var-only-at-top-level instead of no-var as we allow top level
+ // vars.
+ "no-var": "off",
+
+ // Allow using TODO/FIXME comments.
+ "no-warning-comments": "off",
+
+ // Don't require method and property shorthand syntax for object literals.
+ // We use this in the code a lot, but not consistently, and this seems more
+ // like something to check at code review time.
+ "object-shorthand": "off",
+
+ // Allow more than one variable declaration per function.
+ "one-var": "off",
+
+ // Disallow padding within blocks.
+ "padded-blocks": ["warn", "never"],
+
+ // Don't require quotes around object literal property names.
+ "quote-props": "off",
+
+ // Double quotes should be used.
+ "quotes": ["warn", "double", {"avoidEscape": true, "allowTemplateLiterals": true}],
+
+ // Require use of the second argument for parseInt().
+ "radix": "error",
+
+ // Enforce spacing after semicolons.
+ "semi-spacing": ["error", {"before": false, "after": true}],
+
+ // Don't require to sort variables within the same declaration block.
+ // Anyway, one-var is disabled.
+ "sort-vars": "off",
+
+ // Require a space immediately following the // in a line comment.
+ "spaced-comment": ["error", "always"],
+
+ // Require "use strict" to be defined globally in the script.
+ "strict": ["error", "global"],
+
+ // Allow vars to be declared anywhere in the scope.
+ "vars-on-top": "off",
+
+ // Don't require immediate function invocation to be wrapped in parentheses.
+ "wrap-iife": "off",
+
+ // Don't require regex literals to be wrapped in parentheses (which
+ // supposedly prevent them from being mistaken for division operators).
+ "wrap-regex": "off",
+
+ // Disallow Yoda conditions (where literal value comes first).
+ "yoda": "error",
+
+ // disallow use of eval()-like methods
+ "no-implied-eval": "error",
+
+ // Disallow function or variable declarations in nested blocks
+ "no-inner-declarations": "error",
+
+ // Disallow usage of __iterator__ property
+ "no-iterator": "error",
+
+ // Disallow labels that share a name with a variable
+ "no-label-var": "error",
+
+ // Disallow creating new instances of String, Number, and Boolean
+ "no-new-wrappers": "error",
+ },
+};
diff --git a/toolkit/components/webextensions/Extension.jsm b/toolkit/components/webextensions/Extension.jsm
new file mode 100644
index 000000000..3468f2594
--- /dev/null
+++ b/toolkit/components/webextensions/Extension.jsm
@@ -0,0 +1,902 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["Extension", "ExtensionData"];
+
+/* globals Extension ExtensionData */
+
+/*
+ * This file is the main entry point for extensions. When an extension
+ * loads, its bootstrap.js file creates a Extension instance
+ * and calls .startup() on it. It calls .shutdown() when the extension
+ * unloads. Extension manages any extension-specific state in
+ * the chrome process.
+ */
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.importGlobalProperties(["TextEncoder"]);
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionAPIs",
+ "resource://gre/modules/ExtensionAPI.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage",
+ "resource://gre/modules/ExtensionStorage.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestCommon",
+ "resource://testing-common/ExtensionTestCommon.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Locale",
+ "resource://gre/modules/Locale.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Log",
+ "resource://gre/modules/Log.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MatchGlobs",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
+ "resource://gre/modules/Preferences.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "require",
+ "resource://devtools/shared/Loader.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+
+Cu.import("resource://gre/modules/ExtensionContent.jsm");
+Cu.import("resource://gre/modules/ExtensionManagement.jsm");
+Cu.import("resource://gre/modules/ExtensionParent.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "uuidGen",
+ "@mozilla.org/uuid-generator;1",
+ "nsIUUIDGenerator");
+
+var {
+ GlobalManager,
+ ParentAPIManager,
+ apiManager: Management,
+} = ExtensionParent;
+
+const {
+ EventEmitter,
+ LocaleData,
+ getUniqueId,
+} = ExtensionUtils;
+
+XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole);
+
+const LOGGER_ID_BASE = "addons.webextension.";
+const UUID_MAP_PREF = "extensions.webextensions.uuids";
+const LEAVE_STORAGE_PREF = "extensions.webextensions.keepStorageOnUninstall";
+const LEAVE_UUID_PREF = "extensions.webextensions.keepUuidOnUninstall";
+
+const COMMENT_REGEXP = new RegExp(String.raw`
+ ^
+ (
+ (?:
+ [^"\n] |
+ " (?:[^"\\\n] | \\.)* "
+ )*?
+ )
+
+ //.*
+ `.replace(/\s+/g, ""), "gm");
+
+// All moz-extension URIs use a machine-specific UUID rather than the
+// extension's own ID in the host component. This makes it more
+// difficult for web pages to detect whether a user has a given add-on
+// installed (by trying to load a moz-extension URI referring to a
+// web_accessible_resource from the extension). UUIDMap.get()
+// returns the UUID for a given add-on ID.
+var UUIDMap = {
+ _read() {
+ let pref = Preferences.get(UUID_MAP_PREF, "{}");
+ try {
+ return JSON.parse(pref);
+ } catch (e) {
+ Cu.reportError(`Error parsing ${UUID_MAP_PREF}.`);
+ return {};
+ }
+ },
+
+ _write(map) {
+ Preferences.set(UUID_MAP_PREF, JSON.stringify(map));
+ },
+
+ get(id, create = true) {
+ let map = this._read();
+
+ if (id in map) {
+ return map[id];
+ }
+
+ let uuid = null;
+ if (create) {
+ uuid = uuidGen.generateUUID().number;
+ uuid = uuid.slice(1, -1); // Strip { and } off the UUID.
+
+ map[id] = uuid;
+ this._write(map);
+ }
+ return uuid;
+ },
+
+ remove(id) {
+ let map = this._read();
+ delete map[id];
+ this._write(map);
+ },
+};
+
+// This is the old interface that UUIDMap replaced, to be removed when
+// the references listed in bug 1291399 are updated.
+/* exported getExtensionUUID */
+function getExtensionUUID(id) {
+ return UUIDMap.get(id, true);
+}
+
+// For extensions that have called setUninstallURL(), send an event
+// so the browser can display the URL.
+var UninstallObserver = {
+ initialized: false,
+
+ init() {
+ if (!this.initialized) {
+ AddonManager.addAddonListener(this);
+ XPCOMUtils.defineLazyPreferenceGetter(this, "leaveStorage", LEAVE_STORAGE_PREF, false);
+ XPCOMUtils.defineLazyPreferenceGetter(this, "leaveUuid", LEAVE_UUID_PREF, false);
+ this.initialized = true;
+ }
+ },
+
+ onUninstalling(addon) {
+ let extension = GlobalManager.extensionMap.get(addon.id);
+ if (extension) {
+ // Let any other interested listeners respond
+ // (e.g., display the uninstall URL)
+ Management.emit("uninstall", extension);
+ }
+ },
+
+ onUninstalled(addon) {
+ let uuid = UUIDMap.get(addon.id, false);
+ if (!uuid) {
+ return;
+ }
+
+ if (!this.leaveStorage) {
+ // Clear browser.local.storage
+ ExtensionStorage.clear(addon.id);
+
+ // Clear any IndexedDB storage created by the extension
+ let baseURI = NetUtil.newURI(`moz-extension://${uuid}/`);
+ let principal = Services.scriptSecurityManager.createCodebasePrincipal(
+ baseURI, {addonId: addon.id}
+ );
+ Services.qms.clearStoragesForPrincipal(principal);
+
+ // Clear localStorage created by the extension
+ let attrs = JSON.stringify({addonId: addon.id});
+ Services.obs.notifyObservers(null, "clear-origin-attributes-data", attrs);
+ }
+
+ if (!this.leaveUuid) {
+ // Clear the entry in the UUID map
+ UUIDMap.remove(addon.id);
+ }
+ },
+};
+
+UninstallObserver.init();
+
+// Represents the data contained in an extension, contained either
+// in a directory or a zip file, which may or may not be installed.
+// This class implements the functionality of the Extension class,
+// primarily related to manifest parsing and localization, which is
+// useful prior to extension installation or initialization.
+//
+// No functionality of this class is guaranteed to work before
+// |readManifest| has been called, and completed.
+this.ExtensionData = class {
+ constructor(rootURI) {
+ this.rootURI = rootURI;
+
+ this.manifest = null;
+ this.id = null;
+ this.uuid = null;
+ this.localeData = null;
+ this._promiseLocales = null;
+
+ this.apiNames = new Set();
+ this.dependencies = new Set();
+ this.permissions = new Set();
+
+ this.errors = [];
+ }
+
+ get builtinMessages() {
+ return null;
+ }
+
+ get logger() {
+ let id = this.id || "<unknown>";
+ return Log.repository.getLogger(LOGGER_ID_BASE + id);
+ }
+
+ // Report an error about the extension's manifest file.
+ manifestError(message) {
+ this.packagingError(`Reading manifest: ${message}`);
+ }
+
+ // Report an error about the extension's general packaging.
+ packagingError(message) {
+ this.errors.push(message);
+ this.logger.error(`Loading extension '${this.id}': ${message}`);
+ }
+
+ /**
+ * Returns the moz-extension: URL for the given path within this
+ * extension.
+ *
+ * Must not be called unless either the `id` or `uuid` property has
+ * already been set.
+ *
+ * @param {string} path The path portion of the URL.
+ * @returns {string}
+ */
+ getURL(path = "") {
+ if (!(this.id || this.uuid)) {
+ throw new Error("getURL may not be called before an `id` or `uuid` has been set");
+ }
+ if (!this.uuid) {
+ this.uuid = UUIDMap.get(this.id);
+ }
+ return `moz-extension://${this.uuid}/${path}`;
+ }
+
+ readDirectory(path) {
+ return Task.spawn(function* () {
+ if (this.rootURI instanceof Ci.nsIFileURL) {
+ let uri = NetUtil.newURI(this.rootURI.resolve("./" + path));
+ let fullPath = uri.QueryInterface(Ci.nsIFileURL).file.path;
+
+ let iter = new OS.File.DirectoryIterator(fullPath);
+ let results = [];
+
+ try {
+ yield iter.forEach(entry => {
+ results.push(entry);
+ });
+ } catch (e) {
+ // Always return a list, even if the directory does not exist (or is
+ // not a directory) for symmetry with the ZipReader behavior.
+ }
+ iter.close();
+
+ return results;
+ }
+
+ // FIXME: We need a way to do this without main thread IO.
+
+ let uri = this.rootURI.QueryInterface(Ci.nsIJARURI);
+
+ let file = uri.JARFile.QueryInterface(Ci.nsIFileURL).file;
+ let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader);
+ zipReader.open(file);
+ try {
+ let results = [];
+
+ // Normalize the directory path.
+ path = `${uri.JAREntry}/${path}`;
+ path = path.replace(/\/\/+/g, "/").replace(/^\/|\/$/g, "") + "/";
+
+ // Escape pattern metacharacters.
+ let pattern = path.replace(/[[\]()?*~|$\\]/g, "\\$&");
+
+ let enumerator = zipReader.findEntries(pattern + "*");
+ while (enumerator.hasMore()) {
+ let name = enumerator.getNext();
+ if (!name.startsWith(path)) {
+ throw new Error("Unexpected ZipReader entry");
+ }
+
+ // The enumerator returns the full path of all entries.
+ // Trim off the leading path, and filter out entries from
+ // subdirectories.
+ name = name.slice(path.length);
+ if (name && !/\/./.test(name)) {
+ results.push({
+ name: name.replace("/", ""),
+ isDir: name.endsWith("/"),
+ });
+ }
+ }
+
+ return results;
+ } finally {
+ zipReader.close();
+ }
+ }.bind(this));
+ }
+
+ readJSON(path) {
+ return new Promise((resolve, reject) => {
+ let uri = this.rootURI.resolve(`./${path}`);
+
+ NetUtil.asyncFetch({uri, loadUsingSystemPrincipal: true}, (inputStream, status) => {
+ if (!Components.isSuccessCode(status)) {
+ // Convert status code to a string
+ let e = Components.Exception("", status);
+ reject(new Error(`Error while loading '${uri}' (${e.name})`));
+ return;
+ }
+ try {
+ let text = NetUtil.readInputStreamToString(inputStream, inputStream.available(),
+ {charset: "utf-8"});
+
+ text = text.replace(COMMENT_REGEXP, "$1");
+
+ resolve(JSON.parse(text));
+ } catch (e) {
+ reject(e);
+ }
+ });
+ });
+ }
+
+ // Reads the extension's |manifest.json| file, and stores its
+ // parsed contents in |this.manifest|.
+ readManifest() {
+ return Promise.all([
+ this.readJSON("manifest.json"),
+ Management.lazyInit(),
+ ]).then(([manifest]) => {
+ this.manifest = manifest;
+ this.rawManifest = manifest;
+
+ if (manifest && manifest.default_locale) {
+ return this.initLocale();
+ }
+ }).then(() => {
+ let context = {
+ url: this.baseURI && this.baseURI.spec,
+
+ principal: this.principal,
+
+ logError: error => {
+ this.logger.warn(`Loading extension '${this.id}': Reading manifest: ${error}`);
+ },
+
+ preprocessors: {},
+ };
+
+ if (this.localeData) {
+ context.preprocessors.localize = (value, context) => this.localize(value);
+ }
+
+ let normalized = Schemas.normalize(this.manifest, "manifest.WebExtensionManifest", context);
+ if (normalized.error) {
+ this.manifestError(normalized.error);
+ } else {
+ this.manifest = normalized.value;
+ }
+
+ try {
+ // Do not override the add-on id that has been already assigned.
+ if (!this.id && this.manifest.applications.gecko.id) {
+ this.id = this.manifest.applications.gecko.id;
+ }
+ } catch (e) {
+ // Errors are handled by the type checks above.
+ }
+
+ let permissions = this.manifest.permissions || [];
+
+ let whitelist = [];
+ for (let perm of permissions) {
+ this.permissions.add(perm);
+
+ let match = /^(\w+)(?:\.(\w+)(?:\.\w+)*)?$/.exec(perm);
+ if (!match) {
+ whitelist.push(perm);
+ } else if (match[1] == "experiments" && match[2]) {
+ this.apiNames.add(match[2]);
+ }
+ }
+ this.whiteListedHosts = new MatchPattern(whitelist);
+
+ for (let api of this.apiNames) {
+ this.dependencies.add(`${api}@experiments.addons.mozilla.org`);
+ }
+
+ return this.manifest;
+ });
+ }
+
+ localizeMessage(...args) {
+ return this.localeData.localizeMessage(...args);
+ }
+
+ localize(...args) {
+ return this.localeData.localize(...args);
+ }
+
+ // If a "default_locale" is specified in that manifest, returns it
+ // as a Gecko-compatible locale string. Otherwise, returns null.
+ get defaultLocale() {
+ if (this.manifest.default_locale != null) {
+ return this.normalizeLocaleCode(this.manifest.default_locale);
+ }
+
+ return null;
+ }
+
+ // Normalizes a Chrome-compatible locale code to the appropriate
+ // Gecko-compatible variant. Currently, this means simply
+ // replacing underscores with hyphens.
+ normalizeLocaleCode(locale) {
+ return String.replace(locale, /_/g, "-");
+ }
+
+ // Reads the locale file for the given Gecko-compatible locale code, and
+ // stores its parsed contents in |this.localeMessages.get(locale)|.
+ readLocaleFile(locale) {
+ return Task.spawn(function* () {
+ let locales = yield this.promiseLocales();
+ let dir = locales.get(locale) || locale;
+ let file = `_locales/${dir}/messages.json`;
+
+ try {
+ let messages = yield this.readJSON(file);
+ return this.localeData.addLocale(locale, messages, this);
+ } catch (e) {
+ this.packagingError(`Loading locale file ${file}: ${e}`);
+ return new Map();
+ }
+ }.bind(this));
+ }
+
+ // Reads the list of locales available in the extension, and returns a
+ // Promise which resolves to a Map upon completion.
+ // Each map key is a Gecko-compatible locale code, and each value is the
+ // "_locales" subdirectory containing that locale:
+ //
+ // Map(gecko-locale-code -> locale-directory-name)
+ promiseLocales() {
+ if (!this._promiseLocales) {
+ this._promiseLocales = Task.spawn(function* () {
+ let locales = new Map();
+
+ let entries = yield this.readDirectory("_locales");
+ for (let file of entries) {
+ if (file.isDir) {
+ let locale = this.normalizeLocaleCode(file.name);
+ locales.set(locale, file.name);
+ }
+ }
+
+ this.localeData = new LocaleData({
+ defaultLocale: this.defaultLocale,
+ locales,
+ builtinMessages: this.builtinMessages,
+ });
+
+ return locales;
+ }.bind(this));
+ }
+
+ return this._promiseLocales;
+ }
+
+ // Reads the locale messages for all locales, and returns a promise which
+ // resolves to a Map of locale messages upon completion. Each key in the map
+ // is a Gecko-compatible locale code, and each value is a locale data object
+ // as returned by |readLocaleFile|.
+ initAllLocales() {
+ return Task.spawn(function* () {
+ let locales = yield this.promiseLocales();
+
+ yield Promise.all(Array.from(locales.keys(),
+ locale => this.readLocaleFile(locale)));
+
+ let defaultLocale = this.defaultLocale;
+ if (defaultLocale) {
+ if (!locales.has(defaultLocale)) {
+ this.manifestError('Value for "default_locale" property must correspond to ' +
+ 'a directory in "_locales/". Not found: ' +
+ JSON.stringify(`_locales/${this.manifest.default_locale}/`));
+ }
+ } else if (locales.size) {
+ this.manifestError('The "default_locale" property is required when a ' +
+ '"_locales/" directory is present.');
+ }
+
+ return this.localeData.messages;
+ }.bind(this));
+ }
+
+ // Reads the locale file for the given Gecko-compatible locale code, or the
+ // default locale if no locale code is given, and sets it as the currently
+ // selected locale on success.
+ //
+ // Pre-loads the default locale for fallback message processing, regardless
+ // of the locale specified.
+ //
+ // If no locales are unavailable, resolves to |null|.
+ initLocale(locale = this.defaultLocale) {
+ return Task.spawn(function* () {
+ if (locale == null) {
+ return null;
+ }
+
+ let promises = [this.readLocaleFile(locale)];
+
+ let {defaultLocale} = this;
+ if (locale != defaultLocale && !this.localeData.has(defaultLocale)) {
+ promises.push(this.readLocaleFile(defaultLocale));
+ }
+
+ let results = yield Promise.all(promises);
+
+ this.localeData.selectedLocale = locale;
+ return results[0];
+ }.bind(this));
+ }
+};
+
+let _browserUpdated = false;
+
+const PROXIED_EVENTS = new Set(["test-harness-message"]);
+
+// We create one instance of this class per extension. |addonData|
+// comes directly from bootstrap.js when initializing.
+this.Extension = class extends ExtensionData {
+ constructor(addonData, startupReason) {
+ super(addonData.resourceURI);
+
+ this.uuid = UUIDMap.get(addonData.id);
+ this.instanceId = getUniqueId();
+
+ this.MESSAGE_EMIT_EVENT = `Extension:EmitEvent:${this.instanceId}`;
+ Services.ppmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this);
+
+ if (addonData.cleanupFile) {
+ Services.obs.addObserver(this, "xpcom-shutdown", false);
+ this.cleanupFile = addonData.cleanupFile || null;
+ delete addonData.cleanupFile;
+ }
+
+ this.addonData = addonData;
+ this.startupReason = startupReason;
+
+ this.id = addonData.id;
+ this.baseURI = NetUtil.newURI(this.getURL("")).QueryInterface(Ci.nsIURL);
+ this.principal = this.createPrincipal();
+
+ this.onStartup = null;
+
+ this.hasShutdown = false;
+ this.onShutdown = new Set();
+
+ this.uninstallURL = null;
+
+ this.apis = [];
+ this.whiteListedHosts = null;
+ this.webAccessibleResources = null;
+
+ this.emitter = new EventEmitter();
+ }
+
+ static set browserUpdated(updated) {
+ _browserUpdated = updated;
+ }
+
+ static get browserUpdated() {
+ return _browserUpdated;
+ }
+
+ static generateXPI(data) {
+ return ExtensionTestCommon.generateXPI(data);
+ }
+
+ static generateZipFile(files, baseName = "generated-extension.xpi") {
+ return ExtensionTestCommon.generateZipFile(files, baseName);
+ }
+
+ static generate(data) {
+ return ExtensionTestCommon.generate(data);
+ }
+
+ on(hook, f) {
+ return this.emitter.on(hook, f);
+ }
+
+ off(hook, f) {
+ return this.emitter.off(hook, f);
+ }
+
+ emit(event, ...args) {
+ if (PROXIED_EVENTS.has(event)) {
+ Services.ppmm.broadcastAsyncMessage(this.MESSAGE_EMIT_EVENT, {event, args});
+ }
+
+ return this.emitter.emit(event, ...args);
+ }
+
+ receiveMessage({name, data}) {
+ if (name === this.MESSAGE_EMIT_EVENT) {
+ this.emitter.emit(data.event, ...data.args);
+ }
+ }
+
+ testMessage(...args) {
+ this.emit("test-harness-message", ...args);
+ }
+
+ createPrincipal(uri = this.baseURI) {
+ return Services.scriptSecurityManager.createCodebasePrincipal(
+ uri, {addonId: this.id});
+ }
+
+ // Checks that the given URL is a child of our baseURI.
+ isExtensionURL(url) {
+ let uri = Services.io.newURI(url, null, null);
+
+ let common = this.baseURI.getCommonBaseSpec(uri);
+ return common == this.baseURI.spec;
+ }
+
+ readManifest() {
+ return super.readManifest().then(manifest => {
+ if (AppConstants.RELEASE_OR_BETA) {
+ return manifest;
+ }
+
+ // Load Experiments APIs that this extension depends on.
+ return Promise.all(
+ Array.from(this.apiNames, api => ExtensionAPIs.load(api))
+ ).then(apis => {
+ for (let API of apis) {
+ this.apis.push(new API(this));
+ }
+
+ return manifest;
+ });
+ });
+ }
+
+ // Representation of the extension to send to content
+ // processes. This should include anything the content process might
+ // need.
+ serialize() {
+ return {
+ id: this.id,
+ uuid: this.uuid,
+ instanceId: this.instanceId,
+ manifest: this.manifest,
+ resourceURL: this.addonData.resourceURI.spec,
+ baseURL: this.baseURI.spec,
+ content_scripts: this.manifest.content_scripts || [], // eslint-disable-line camelcase
+ webAccessibleResources: this.webAccessibleResources.serialize(),
+ whiteListedHosts: this.whiteListedHosts.serialize(),
+ localeData: this.localeData.serialize(),
+ permissions: this.permissions,
+ principal: this.principal,
+ };
+ }
+
+ broadcast(msg, data) {
+ return new Promise(resolve => {
+ let count = Services.ppmm.childCount;
+ Services.ppmm.addMessageListener(msg + "Complete", function listener() {
+ count--;
+ if (count == 0) {
+ Services.ppmm.removeMessageListener(msg + "Complete", listener);
+ resolve();
+ }
+ });
+ Services.ppmm.broadcastAsyncMessage(msg, data);
+ });
+ }
+
+ runManifest(manifest) {
+ // Strip leading slashes from web_accessible_resources.
+ let strippedWebAccessibleResources = [];
+ if (manifest.web_accessible_resources) {
+ strippedWebAccessibleResources = manifest.web_accessible_resources.map(path => path.replace(/^\/+/, ""));
+ }
+
+ this.webAccessibleResources = new MatchGlobs(strippedWebAccessibleResources);
+
+ let promises = [];
+ for (let directive in manifest) {
+ if (manifest[directive] !== null) {
+ promises.push(Management.emit(`manifest_${directive}`, directive, this, manifest));
+ }
+ }
+
+ let data = Services.ppmm.initialProcessData;
+ if (!data["Extension:Extensions"]) {
+ data["Extension:Extensions"] = [];
+ }
+ let serial = this.serialize();
+ data["Extension:Extensions"].push(serial);
+
+ return this.broadcast("Extension:Startup", serial).then(() => {
+ return Promise.all(promises);
+ });
+ }
+
+ callOnClose(obj) {
+ this.onShutdown.add(obj);
+ }
+
+ forgetOnClose(obj) {
+ this.onShutdown.delete(obj);
+ }
+
+ get builtinMessages() {
+ return new Map([
+ ["@@extension_id", this.uuid],
+ ]);
+ }
+
+ // Reads the locale file for the given Gecko-compatible locale code, or if
+ // no locale is given, the available locale closest to the UI locale.
+ // Sets the currently selected locale on success.
+ initLocale(locale = undefined) {
+ // Ugh.
+ let super_ = super.initLocale.bind(this);
+
+ return Task.spawn(function* () {
+ if (locale === undefined) {
+ let locales = yield this.promiseLocales();
+
+ let localeList = Array.from(locales.keys(), locale => {
+ return {name: locale, locales: [locale]};
+ });
+
+ let match = Locale.findClosestLocale(localeList);
+ locale = match ? match.name : this.defaultLocale;
+ }
+
+ return super_(locale);
+ }.bind(this));
+ }
+
+ startup() {
+ let started = false;
+ return this.readManifest().then(() => {
+ ExtensionManagement.startupExtension(this.uuid, this.addonData.resourceURI, this);
+ started = true;
+
+ if (!this.hasShutdown) {
+ return this.initLocale();
+ }
+ }).then(() => {
+ if (this.errors.length) {
+ return Promise.reject({errors: this.errors});
+ }
+
+ if (this.hasShutdown) {
+ return;
+ }
+
+ GlobalManager.init(this);
+
+ // The "startup" Management event sent on the extension instance itself
+ // is emitted just before the Management "startup" event,
+ // and it is used to run code that needs to be executed before
+ // any of the "startup" listeners.
+ this.emit("startup", this);
+ Management.emit("startup", this);
+
+ return this.runManifest(this.manifest);
+ }).then(() => {
+ Management.emit("ready", this);
+ }).catch(e => {
+ dump(`Extension error: ${e.message} ${e.filename || e.fileName}:${e.lineNumber} :: ${e.stack || new Error().stack}\n`);
+ Cu.reportError(e);
+
+ if (started) {
+ ExtensionManagement.shutdownExtension(this.uuid);
+ }
+
+ this.cleanupGeneratedFile();
+
+ throw e;
+ });
+ }
+
+ cleanupGeneratedFile() {
+ if (!this.cleanupFile) {
+ return;
+ }
+
+ let file = this.cleanupFile;
+ this.cleanupFile = null;
+
+ Services.obs.removeObserver(this, "xpcom-shutdown");
+
+ this.broadcast("Extension:FlushJarCache", {path: file.path}).then(() => {
+ // We can't delete this file until everyone using it has
+ // closed it (because Windows is dumb). So we wait for all the
+ // child processes (including the parent) to flush their JAR
+ // caches. These caches may keep the file open.
+ file.remove(false);
+ });
+ }
+
+ shutdown() {
+ this.hasShutdown = true;
+
+ Services.ppmm.removeMessageListener(this.MESSAGE_EMIT_EVENT, this);
+
+ if (!this.manifest) {
+ ExtensionManagement.shutdownExtension(this.uuid);
+
+ this.cleanupGeneratedFile();
+ return;
+ }
+
+ GlobalManager.uninit(this);
+
+ for (let obj of this.onShutdown) {
+ obj.close();
+ }
+
+ for (let api of this.apis) {
+ api.destroy();
+ }
+
+ ParentAPIManager.shutdownExtension(this.id);
+
+ Management.emit("shutdown", this);
+
+ Services.ppmm.broadcastAsyncMessage("Extension:Shutdown", {id: this.id});
+
+ MessageChannel.abortResponses({extensionId: this.id});
+
+ ExtensionManagement.shutdownExtension(this.uuid);
+
+ this.cleanupGeneratedFile();
+ }
+
+ observe(subject, topic, data) {
+ if (topic == "xpcom-shutdown") {
+ this.cleanupGeneratedFile();
+ }
+ }
+
+ hasPermission(perm) {
+ let match = /^manifest:(.*)/.exec(perm);
+ if (match) {
+ return this.manifest[match[1]] != null;
+ }
+
+ return this.permissions.has(perm);
+ }
+
+ get name() {
+ return this.manifest.name;
+ }
+};
diff --git a/toolkit/components/webextensions/ExtensionAPI.jsm b/toolkit/components/webextensions/ExtensionAPI.jsm
new file mode 100644
index 000000000..54dab8e3b
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionAPI.jsm
@@ -0,0 +1,81 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionAPI", "ExtensionAPIs"];
+
+/* exported ExtensionAPIs */
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://gre/modules/ExtensionManagement.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter",
+ "resource://devtools/shared/event-emitter.js");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+
+const global = this;
+
+class ExtensionAPI {
+ constructor(extension) {
+ this.extension = extension;
+ }
+
+ destroy() {
+ }
+
+ getAPI(context) {
+ throw new Error("Not Implemented");
+ }
+}
+
+var ExtensionAPIs = {
+ apis: ExtensionManagement.APIs.apis,
+
+ load(apiName) {
+ let api = this.apis.get(apiName);
+
+ if (api.loadPromise) {
+ return api.loadPromise;
+ }
+
+ let {script, schema} = api;
+
+ let addonId = `${apiName}@experiments.addons.mozilla.org`;
+ api.sandbox = Cu.Sandbox(global, {
+ wantXrays: false,
+ sandboxName: script,
+ addonId,
+ metadata: {addonID: addonId},
+ });
+
+ api.sandbox.ExtensionAPI = ExtensionAPI;
+
+ Services.scriptloader.loadSubScript(script, api.sandbox, "UTF-8");
+
+ api.loadPromise = Schemas.load(schema).then(() => {
+ return Cu.evalInSandbox("API", api.sandbox);
+ });
+
+ return api.loadPromise;
+ },
+
+ unload(apiName) {
+ let api = this.apis.get(apiName);
+
+ let {schema} = api;
+
+ Schemas.unload(schema);
+ Cu.nukeSandbox(api.sandbox);
+
+ api.sandbox = null;
+ api.loadPromise = null;
+ },
+};
diff --git a/toolkit/components/webextensions/ExtensionChild.jsm b/toolkit/components/webextensions/ExtensionChild.jsm
new file mode 100644
index 000000000..c953dd685
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionChild.jsm
@@ -0,0 +1,1040 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionChild"];
+
+/*
+ * This file handles addon logic that is independent of the chrome process.
+ * When addons run out-of-process, this is the main entry point.
+ * Its primary function is managing addon globals.
+ *
+ * Don't put contentscript logic here, use ExtensionContent.jsm instead.
+ */
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NativeApp",
+ "resource://gre/modules/NativeMessaging.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
+ "resource://gre/modules/PromiseUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+
+const CATEGORY_EXTENSION_SCRIPTS_ADDON = "webextension-scripts-addon";
+
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+const {
+ DefaultMap,
+ EventManager,
+ SingletonEventManager,
+ SpreadArgs,
+ defineLazyGetter,
+ getInnerWindowID,
+ getMessageManager,
+ getUniqueId,
+ injectAPI,
+} = ExtensionUtils;
+
+const {
+ BaseContext,
+ LocalAPIImplementation,
+ SchemaAPIInterface,
+ SchemaAPIManager,
+} = ExtensionCommon;
+
+var ExtensionChild;
+
+/**
+ * Abstraction for a Port object in the extension API.
+ *
+ * @param {BaseContext} context The context that owns this port.
+ * @param {nsIMessageSender} senderMM The message manager to send messages to.
+ * @param {Array<nsIMessageListenerManager>} receiverMMs Message managers to
+ * listen on.
+ * @param {string} name Arbitrary port name as defined by the addon.
+ * @param {string} id An ID that uniquely identifies this port's channel.
+ * @param {object} sender The `port.sender` property.
+ * @param {object} recipient The recipient of messages sent from this port.
+ */
+class Port {
+ constructor(context, senderMM, receiverMMs, name, id, sender, recipient) {
+ this.context = context;
+ this.senderMM = senderMM;
+ this.receiverMMs = receiverMMs;
+ this.name = name;
+ this.id = id;
+ this.sender = sender;
+ this.recipient = recipient;
+ this.disconnected = false;
+ this.disconnectListeners = new Set();
+ this.unregisterMessageFuncs = new Set();
+
+ // Common options for onMessage and onDisconnect.
+ this.handlerBase = {
+ messageFilterStrict: {portId: id},
+
+ filterMessage: (sender, recipient) => {
+ return sender.contextId !== this.context.contextId;
+ },
+ };
+
+ this.disconnectHandler = Object.assign({
+ receiveMessage: ({data}) => this.disconnectByOtherEnd(data),
+ }, this.handlerBase);
+
+ MessageChannel.addListener(this.receiverMMs, "Extension:Port:Disconnect", this.disconnectHandler);
+
+ this.context.callOnClose(this);
+ }
+
+ api() {
+ let portObj = Cu.createObjectIn(this.context.cloneScope);
+
+ let portError = null;
+ let publicAPI = {
+ name: this.name,
+
+ disconnect: () => {
+ this.disconnect();
+ },
+
+ postMessage: json => {
+ this.postMessage(json);
+ },
+
+ onDisconnect: new EventManager(this.context, "Port.onDisconnect", fire => {
+ return this.registerOnDisconnect(error => {
+ portError = error && this.context.normalizeError(error);
+ fire.withoutClone(portObj);
+ });
+ }).api(),
+
+ onMessage: new EventManager(this.context, "Port.onMessage", fire => {
+ return this.registerOnMessage(msg => {
+ msg = Cu.cloneInto(msg, this.context.cloneScope);
+ fire.withoutClone(msg, portObj);
+ });
+ }).api(),
+
+ get error() {
+ return portError;
+ },
+ };
+
+ if (this.sender) {
+ publicAPI.sender = this.sender;
+ }
+
+ injectAPI(publicAPI, portObj);
+ return portObj;
+ }
+
+ postMessage(json) {
+ if (this.disconnected) {
+ throw new this.context.cloneScope.Error("Attempt to postMessage on disconnected port");
+ }
+
+ this._sendMessage("Extension:Port:PostMessage", json);
+ }
+
+ /**
+ * Register a callback that is called when the port is disconnected by the
+ * *other* end. The callback is automatically unregistered when the port or
+ * context is closed.
+ *
+ * @param {function} callback Called when the other end disconnects the port.
+ * If the disconnect is caused by an error, the first parameter is an
+ * object with a "message" string property that describes the cause.
+ * @returns {function} Function to unregister the listener.
+ */
+ registerOnDisconnect(callback) {
+ let listener = error => {
+ if (this.context.active && !this.disconnected) {
+ callback(error);
+ }
+ };
+ this.disconnectListeners.add(listener);
+ return () => {
+ this.disconnectListeners.delete(listener);
+ };
+ }
+
+ /**
+ * Register a callback that is called when a message is received. The callback
+ * is automatically unregistered when the port or context is closed.
+ *
+ * @param {function} callback Called when a message is received.
+ * @returns {function} Function to unregister the listener.
+ */
+ registerOnMessage(callback) {
+ let handler = Object.assign({
+ receiveMessage: ({data}) => {
+ if (this.context.active && !this.disconnected) {
+ callback(data);
+ }
+ },
+ }, this.handlerBase);
+
+ let unregister = () => {
+ this.unregisterMessageFuncs.delete(unregister);
+ MessageChannel.removeListener(this.receiverMMs, "Extension:Port:PostMessage", handler);
+ };
+ MessageChannel.addListener(this.receiverMMs, "Extension:Port:PostMessage", handler);
+ this.unregisterMessageFuncs.add(unregister);
+ return unregister;
+ }
+
+ _sendMessage(message, data) {
+ let options = {
+ recipient: Object.assign({}, this.recipient, {portId: this.id}),
+ responseType: MessageChannel.RESPONSE_NONE,
+ };
+
+ return this.context.sendMessage(this.senderMM, message, data, options);
+ }
+
+ handleDisconnection() {
+ MessageChannel.removeListener(this.receiverMMs, "Extension:Port:Disconnect", this.disconnectHandler);
+ for (let unregister of this.unregisterMessageFuncs) {
+ unregister();
+ }
+ this.context.forgetOnClose(this);
+ this.disconnected = true;
+ }
+
+ /**
+ * Disconnect the port from the other end (which may not even exist).
+ *
+ * @param {Error|{message: string}} [error] The reason for disconnecting,
+ * if it is an abnormal disconnect.
+ */
+ disconnectByOtherEnd(error = null) {
+ if (this.disconnected) {
+ return;
+ }
+
+ for (let listener of this.disconnectListeners) {
+ listener(error);
+ }
+
+ this.handleDisconnection();
+ }
+
+ /**
+ * Disconnect the port from this end.
+ *
+ * @param {Error|{message: string}} [error] The reason for disconnecting,
+ * if it is an abnormal disconnect.
+ */
+ disconnect(error = null) {
+ if (this.disconnected) {
+ // disconnect() may be called without side effects even after the port is
+ // closed - https://developer.chrome.com/extensions/runtime#type-Port
+ return;
+ }
+ this.handleDisconnection();
+ if (error) {
+ error = {message: this.context.normalizeError(error).message};
+ }
+ this._sendMessage("Extension:Port:Disconnect", error);
+ }
+
+ close() {
+ this.disconnect();
+ }
+}
+
+class NativePort extends Port {
+ postMessage(data) {
+ data = NativeApp.encodeMessage(this.context, data);
+
+ return super.postMessage(data);
+ }
+}
+
+/**
+ * Each extension context gets its own Messenger object. It handles the
+ * basics of sendMessage, onMessage, connect and onConnect.
+ *
+ * @param {BaseContext} context The context to which this Messenger is tied.
+ * @param {Array<nsIMessageListenerManager>} messageManagers
+ * The message managers used to receive messages (e.g. onMessage/onConnect
+ * requests).
+ * @param {object} sender Describes this sender to the recipient. This object
+ * is extended further by BaseContext's sendMessage method and appears as
+ * the `sender` object to `onConnect` and `onMessage`.
+ * Do not set the `extensionId`, `contextId` or `tab` properties. The former
+ * two are added by BaseContext's sendMessage, while `sender.tab` is set by
+ * the ProxyMessenger in the main process.
+ * @param {object} filter A recipient filter to apply to incoming messages from
+ * the broker. Messages are only handled by this Messenger if all key-value
+ * pairs match the `recipient` as specified by the sender of the message.
+ * In other words, this filter defines the required fields of `recipient`.
+ * @param {object} [optionalFilter] An additional filter to apply to incoming
+ * messages. Unlike `filter`, the keys from `optionalFilter` are allowed to
+ * be omitted from `recipient`. Only keys that are present in both
+ * `optionalFilter` and `recipient` are applied to filter incoming messages.
+ */
+class Messenger {
+ constructor(context, messageManagers, sender, filter, optionalFilter) {
+ this.context = context;
+ this.messageManagers = messageManagers;
+ this.sender = sender;
+ this.filter = filter;
+ this.optionalFilter = optionalFilter;
+ }
+
+ _sendMessage(messageManager, message, data, recipient) {
+ let options = {
+ recipient,
+ sender: this.sender,
+ responseType: MessageChannel.RESPONSE_FIRST,
+ };
+
+ return this.context.sendMessage(messageManager, message, data, options);
+ }
+
+ sendMessage(messageManager, msg, recipient, responseCallback) {
+ let promise = this._sendMessage(messageManager, "Extension:Message", msg, recipient)
+ .catch(error => {
+ if (error.result == MessageChannel.RESULT_NO_HANDLER) {
+ return Promise.reject({message: "Could not establish connection. Receiving end does not exist."});
+ } else if (error.result != MessageChannel.RESULT_NO_RESPONSE) {
+ return Promise.reject({message: error.message});
+ }
+ });
+
+ return this.context.wrapPromise(promise, responseCallback);
+ }
+
+ sendNativeMessage(messageManager, msg, recipient, responseCallback) {
+ msg = NativeApp.encodeMessage(this.context, msg);
+ return this.sendMessage(messageManager, msg, recipient, responseCallback);
+ }
+
+ onMessage(name) {
+ return new SingletonEventManager(this.context, name, callback => {
+ let listener = {
+ messageFilterPermissive: this.optionalFilter,
+ messageFilterStrict: this.filter,
+
+ filterMessage: (sender, recipient) => {
+ // Ignore the message if it was sent by this Messenger.
+ return sender.contextId !== this.context.contextId;
+ },
+
+ receiveMessage: ({target, data: message, sender, recipient}) => {
+ if (!this.context.active) {
+ return;
+ }
+
+ let sendResponse;
+ let response = undefined;
+ let promise = new Promise(resolve => {
+ sendResponse = value => {
+ resolve(value);
+ response = promise;
+ };
+ });
+
+ message = Cu.cloneInto(message, this.context.cloneScope);
+ sender = Cu.cloneInto(sender, this.context.cloneScope);
+ sendResponse = Cu.exportFunction(sendResponse, this.context.cloneScope);
+
+ // Note: We intentionally do not use runSafe here so that any
+ // errors are propagated to the message sender.
+ let result = callback(message, sender, sendResponse);
+ if (result instanceof this.context.cloneScope.Promise) {
+ return result;
+ } else if (result === true) {
+ return promise;
+ }
+ return response;
+ },
+ };
+
+ MessageChannel.addListener(this.messageManagers, "Extension:Message", listener);
+ return () => {
+ MessageChannel.removeListener(this.messageManagers, "Extension:Message", listener);
+ };
+ }).api();
+ }
+
+ _connect(messageManager, port, recipient) {
+ let msg = {
+ name: port.name,
+ portId: port.id,
+ };
+
+ this._sendMessage(messageManager, "Extension:Connect", msg, recipient).catch(error => {
+ if (error.result === MessageChannel.RESULT_NO_HANDLER) {
+ error = {message: "Could not establish connection. Receiving end does not exist."};
+ } else if (error.result === MessageChannel.RESULT_DISCONNECTED) {
+ error = null;
+ }
+ port.disconnectByOtherEnd(error);
+ });
+
+ return port.api();
+ }
+
+ connect(messageManager, name, recipient) {
+ let portId = getUniqueId();
+
+ let port = new Port(this.context, messageManager, this.messageManagers, name, portId, null, recipient);
+
+ return this._connect(messageManager, port, recipient);
+ }
+
+ connectNative(messageManager, name, recipient) {
+ let portId = getUniqueId();
+
+ let port = new NativePort(this.context, messageManager, this.messageManagers, name, portId, null, recipient);
+
+ return this._connect(messageManager, port, recipient);
+ }
+
+ onConnect(name) {
+ return new SingletonEventManager(this.context, name, callback => {
+ let listener = {
+ messageFilterPermissive: this.optionalFilter,
+ messageFilterStrict: this.filter,
+
+ filterMessage: (sender, recipient) => {
+ // Ignore the port if it was created by this Messenger.
+ return sender.contextId !== this.context.contextId;
+ },
+
+ receiveMessage: ({target, data: message, sender}) => {
+ let {name, portId} = message;
+ let mm = getMessageManager(target);
+ let recipient = Object.assign({}, sender);
+ if (recipient.tab) {
+ recipient.tabId = recipient.tab.id;
+ delete recipient.tab;
+ }
+ let port = new Port(this.context, mm, this.messageManagers, name, portId, sender, recipient);
+ this.context.runSafeWithoutClone(callback, port.api());
+ return true;
+ },
+ };
+
+ MessageChannel.addListener(this.messageManagers, "Extension:Connect", listener);
+ return () => {
+ MessageChannel.removeListener(this.messageManagers, "Extension:Connect", listener);
+ };
+ }).api();
+ }
+}
+
+var apiManager = new class extends SchemaAPIManager {
+ constructor() {
+ super("addon");
+ this.initialized = false;
+ }
+
+ generateAPIs(...args) {
+ if (!this.initialized) {
+ this.initialized = true;
+ for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS_ADDON)) {
+ this.loadScript(value);
+ }
+ }
+ return super.generateAPIs(...args);
+ }
+
+ registerSchemaAPI(namespace, envType, getAPI) {
+ if (envType == "addon_child") {
+ super.registerSchemaAPI(namespace, envType, getAPI);
+ }
+ }
+}();
+
+/**
+ * An object that runs an remote implementation of an API.
+ */
+class ProxyAPIImplementation extends SchemaAPIInterface {
+ /**
+ * @param {string} namespace The full path to the namespace that contains the
+ * `name` member. This may contain dots, e.g. "storage.local".
+ * @param {string} name The name of the method or property.
+ * @param {ChildAPIManager} childApiManager The owner of this implementation.
+ */
+ constructor(namespace, name, childApiManager) {
+ super();
+ this.path = `${namespace}.${name}`;
+ this.childApiManager = childApiManager;
+ }
+
+ callFunctionNoReturn(args) {
+ this.childApiManager.callParentFunctionNoReturn(this.path, args);
+ }
+
+ callAsyncFunction(args, callback) {
+ return this.childApiManager.callParentAsyncFunction(this.path, args, callback);
+ }
+
+ addListener(listener, args) {
+ let map = this.childApiManager.listeners.get(this.path);
+
+ if (map.listeners.has(listener)) {
+ // TODO: Called with different args?
+ return;
+ }
+
+ let id = getUniqueId();
+
+ map.ids.set(id, listener);
+ map.listeners.set(listener, id);
+
+ this.childApiManager.messageManager.sendAsyncMessage("API:AddListener", {
+ childId: this.childApiManager.id,
+ listenerId: id,
+ path: this.path,
+ args,
+ });
+ }
+
+ removeListener(listener) {
+ let map = this.childApiManager.listeners.get(this.path);
+
+ if (!map.listeners.has(listener)) {
+ return;
+ }
+
+ let id = map.listeners.get(listener);
+ map.listeners.delete(listener);
+ map.ids.delete(id);
+
+ this.childApiManager.messageManager.sendAsyncMessage("API:RemoveListener", {
+ childId: this.childApiManager.id,
+ listenerId: id,
+ path: this.path,
+ });
+ }
+
+ hasListener(listener) {
+ let map = this.childApiManager.listeners.get(this.path);
+ return map.listeners.has(listener);
+ }
+}
+
+// We create one instance of this class for every extension context that
+// needs to use remote APIs. It uses the message manager to communicate
+// with the ParentAPIManager singleton in ExtensionParent.jsm. It
+// handles asynchronous function calls as well as event listeners.
+class ChildAPIManager {
+ constructor(context, messageManager, localApis, contextData) {
+ this.context = context;
+ this.messageManager = messageManager;
+ this.url = contextData.url;
+
+ // The root namespace of all locally implemented APIs. If an extension calls
+ // an API that does not exist in this object, then the implementation is
+ // delegated to the ParentAPIManager.
+ this.localApis = localApis;
+
+ this.id = `${context.extension.id}.${context.contextId}`;
+
+ MessageChannel.addListener(messageManager, "API:RunListener", this);
+ messageManager.addMessageListener("API:CallResult", this);
+
+ this.messageFilterStrict = {childId: this.id};
+
+ this.listeners = new DefaultMap(() => ({
+ ids: new Map(),
+ listeners: new Map(),
+ }));
+
+ // Map[callId -> Deferred]
+ this.callPromises = new Map();
+
+ let params = {
+ childId: this.id,
+ extensionId: context.extension.id,
+ principal: context.principal,
+ };
+ Object.assign(params, contextData);
+
+ this.messageManager.sendAsyncMessage("API:CreateProxyContext", params);
+ }
+
+ receiveMessage({name, messageName, data}) {
+ if (data.childId != this.id) {
+ return;
+ }
+
+ switch (name || messageName) {
+ case "API:RunListener":
+ let map = this.listeners.get(data.path);
+ let listener = map.ids.get(data.listenerId);
+
+ if (listener) {
+ return this.context.runSafe(listener, ...data.args);
+ }
+
+ Cu.reportError(`Unknown listener at childId=${data.childId} path=${data.path} listenerId=${data.listenerId}\n`);
+ break;
+
+ case "API:CallResult":
+ let deferred = this.callPromises.get(data.callId);
+ if ("error" in data) {
+ deferred.reject(data.error);
+ } else {
+ deferred.resolve(new SpreadArgs(data.result));
+ }
+ this.callPromises.delete(data.callId);
+ break;
+ }
+ }
+
+ /**
+ * Call a function in the parent process and ignores its return value.
+ *
+ * @param {string} path The full name of the method, e.g. "tabs.create".
+ * @param {Array} args The parameters for the function.
+ */
+ callParentFunctionNoReturn(path, args) {
+ this.messageManager.sendAsyncMessage("API:Call", {
+ childId: this.id,
+ path,
+ args,
+ });
+ }
+
+ /**
+ * Calls a function in the parent process and returns its result
+ * asynchronously.
+ *
+ * @param {string} path The full name of the method, e.g. "tabs.create".
+ * @param {Array} args The parameters for the function.
+ * @param {function(*)} [callback] The callback to be called when the function
+ * completes.
+ * @returns {Promise|undefined} Must be void if `callback` is set, and a
+ * promise otherwise. The promise is resolved when the function completes.
+ */
+ callParentAsyncFunction(path, args, callback) {
+ let callId = getUniqueId();
+ let deferred = PromiseUtils.defer();
+ this.callPromises.set(callId, deferred);
+
+ this.messageManager.sendAsyncMessage("API:Call", {
+ childId: this.id,
+ callId,
+ path,
+ args,
+ });
+
+ return this.context.wrapPromise(deferred.promise, callback);
+ }
+
+ /**
+ * Create a proxy for an event in the parent process. The returned event
+ * object shares its internal state with other instances. For instance, if
+ * `removeListener` is used on a listener that was added on another object
+ * through `addListener`, then the event is unregistered.
+ *
+ * @param {string} path The full name of the event, e.g. "tabs.onCreated".
+ * @returns {object} An object with the addListener, removeListener and
+ * hasListener methods. See SchemaAPIInterface for documentation.
+ */
+ getParentEvent(path) {
+ path = path.split(".");
+
+ let name = path.pop();
+ let namespace = path.join(".");
+
+ let impl = new ProxyAPIImplementation(namespace, name, this);
+ return {
+ addListener: (listener, ...args) => impl.addListener(listener, args),
+ removeListener: (listener) => impl.removeListener(listener),
+ hasListener: (listener) => impl.hasListener(listener),
+ };
+ }
+
+ close() {
+ this.messageManager.sendAsyncMessage("API:CloseProxyContext", {childId: this.id});
+ }
+
+ get cloneScope() {
+ return this.context.cloneScope;
+ }
+
+ get principal() {
+ return this.context.principal;
+ }
+
+ shouldInject(namespace, name, allowedContexts) {
+ // Do not generate content script APIs, unless explicitly allowed.
+ if (this.context.envType === "content_child" &&
+ !allowedContexts.includes("content")) {
+ return false;
+ }
+ if (allowedContexts.includes("addon_parent_only")) {
+ return false;
+ }
+ return true;
+ }
+
+ getImplementation(namespace, name) {
+ let obj = namespace.split(".").reduce(
+ (object, prop) => object && object[prop],
+ this.localApis);
+
+ if (obj && name in obj) {
+ return new LocalAPIImplementation(obj, name, this.context);
+ }
+
+ return this.getFallbackImplementation(namespace, name);
+ }
+
+ getFallbackImplementation(namespace, name) {
+ // No local API found, defer implementation to the parent.
+ return new ProxyAPIImplementation(namespace, name, this);
+ }
+
+ hasPermission(permission) {
+ return this.context.extension.hasPermission(permission);
+ }
+}
+
+class ExtensionPageContextChild extends BaseContext {
+ /**
+ * This ExtensionPageContextChild represents a privileged addon
+ * execution environment that has full access to the WebExtensions
+ * APIs (provided that the correct permissions have been requested).
+ *
+ * This is the child side of the ExtensionPageContextParent class
+ * defined in ExtensionParent.jsm.
+ *
+ * @param {BrowserExtensionContent} extension This context's owner.
+ * @param {object} params
+ * @param {nsIDOMWindow} params.contentWindow The window where the addon runs.
+ * @param {string} params.viewType One of "background", "popup" or "tab".
+ * "background" and "tab" are used by `browser.extension.getViews`.
+ * "popup" is only used internally to identify page action and browser
+ * action popups and options_ui pages.
+ * @param {number} [params.tabId] This tab's ID, used if viewType is "tab".
+ */
+ constructor(extension, params) {
+ super("addon_child", extension);
+ if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) {
+ // This check is temporary. It should be removed once the proxy creation
+ // is asynchronous.
+ throw new Error("ExtensionPageContextChild cannot be created in child processes");
+ }
+
+ let {viewType, uri, contentWindow, tabId} = params;
+ this.viewType = viewType;
+ this.uri = uri || extension.baseURI;
+
+ this.setContentWindow(contentWindow);
+
+ // This is the MessageSender property passed to extension.
+ // It can be augmented by the "page-open" hook.
+ let sender = {id: extension.uuid};
+ if (viewType == "tab") {
+ sender.tabId = tabId;
+ this.tabId = tabId;
+ }
+ if (uri) {
+ sender.url = uri.spec;
+ }
+ this.sender = sender;
+
+ Schemas.exportLazyGetter(contentWindow, "browser", () => {
+ let browserObj = Cu.createObjectIn(contentWindow);
+ Schemas.inject(browserObj, this.childManager);
+ return browserObj;
+ });
+
+ Schemas.exportLazyGetter(contentWindow, "chrome", () => {
+ let chromeApiWrapper = Object.create(this.childManager);
+ chromeApiWrapper.isChromeCompat = true;
+
+ let chromeObj = Cu.createObjectIn(contentWindow);
+ Schemas.inject(chromeObj, chromeApiWrapper);
+ return chromeObj;
+ });
+
+ this.extension.views.add(this);
+ }
+
+ get cloneScope() {
+ return this.contentWindow;
+ }
+
+ get principal() {
+ return this.contentWindow.document.nodePrincipal;
+ }
+
+ get windowId() {
+ if (this.viewType == "tab" || this.viewType == "popup") {
+ let globalView = ExtensionChild.contentGlobals.get(this.messageManager);
+ return globalView ? globalView.windowId : -1;
+ }
+ }
+
+ // Called when the extension shuts down.
+ shutdown() {
+ this.unload();
+ }
+
+ // This method is called when an extension page navigates away or
+ // its tab is closed.
+ unload() {
+ // Note that without this guard, we end up running unload code
+ // multiple times for tab pages closed by the "page-unload" handlers
+ // triggered below.
+ if (this.unloaded) {
+ return;
+ }
+
+ if (this.contentWindow) {
+ this.contentWindow.close();
+ }
+
+ super.unload();
+ this.extension.views.delete(this);
+ }
+}
+
+defineLazyGetter(ExtensionPageContextChild.prototype, "messenger", function() {
+ let filter = {extensionId: this.extension.id};
+ let optionalFilter = {};
+ // Addon-generated messages (not necessarily from the same process as the
+ // addon itself) are sent to the main process, which forwards them via the
+ // parent process message manager. Specific replies can be sent to the frame
+ // message manager.
+ return new Messenger(this, [Services.cpmm, this.messageManager], this.sender,
+ filter, optionalFilter);
+});
+
+defineLazyGetter(ExtensionPageContextChild.prototype, "childManager", function() {
+ let localApis = {};
+ apiManager.generateAPIs(this, localApis);
+
+ if (this.viewType == "background") {
+ apiManager.global.initializeBackgroundPage(this.contentWindow);
+ }
+
+ let childManager = new ChildAPIManager(this, this.messageManager, localApis, {
+ envType: "addon_parent",
+ viewType: this.viewType,
+ url: this.uri.spec,
+ incognito: this.incognito,
+ });
+
+ this.callOnClose(childManager);
+
+ return childManager;
+});
+
+// All subframes in a tab, background page, popup, etc. have the same view type.
+// This class keeps track of such global state.
+// Note that this is created even for non-extension tabs because at present we
+// do not have a way to distinguish regular tabs from extension tabs at the
+// initialization of a frame script.
+class ContentGlobal {
+ /**
+ * @param {nsIContentFrameMessageManager} global The frame script's global.
+ */
+ constructor(global) {
+ this.global = global;
+ // Unless specified otherwise assume that the extension page is in a tab,
+ // because the majority of all class instances are going to be a tab. Any
+ // special views (background page, extension popup) will immediately send an
+ // Extension:InitExtensionView message to change the viewType.
+ this.viewType = "tab";
+ this.tabId = -1;
+ this.windowId = -1;
+ this.initialized = false;
+ this.global.addMessageListener("Extension:InitExtensionView", this);
+ this.global.addMessageListener("Extension:SetTabAndWindowId", this);
+
+ this.initialDocuments = new WeakSet();
+ }
+
+ uninit() {
+ this.global.removeMessageListener("Extension:InitExtensionView", this);
+ this.global.removeMessageListener("Extension:SetTabAndWindowId", this);
+ this.global.removeEventListener("DOMContentLoaded", this);
+ }
+
+ ensureInitialized() {
+ if (!this.initialized) {
+ // Request tab and window ID in case "Extension:InitExtensionView" is not
+ // sent (e.g. when `viewType` is "tab").
+ let reply = this.global.sendSyncMessage("Extension:GetTabAndWindowId");
+ this.handleSetTabAndWindowId(reply[0] || {});
+ }
+ return this;
+ }
+
+ receiveMessage({name, data}) {
+ switch (name) {
+ case "Extension:InitExtensionView":
+ // The view type is initialized once and then fixed.
+ this.global.removeMessageListener("Extension:InitExtensionView", this);
+ let {viewType, url} = data;
+ this.viewType = viewType;
+ this.global.addEventListener("DOMContentLoaded", this);
+ if (url) {
+ // TODO(robwu): Remove this check. It is only here because the popup
+ // implementation does not always load a URL at the initialization,
+ // and the logic is too complex to fix at once.
+ let {document} = this.global.content;
+ this.initialDocuments.add(document);
+ document.location.replace(url);
+ }
+ /* Falls through to allow these properties to be initialized at once */
+ case "Extension:SetTabAndWindowId":
+ this.handleSetTabAndWindowId(data);
+ break;
+ }
+ }
+
+ handleSetTabAndWindowId(data) {
+ let {tabId, windowId} = data;
+ if (tabId) {
+ // Tab IDs are not expected to change.
+ if (this.tabId !== -1 && tabId !== this.tabId) {
+ throw new Error("Attempted to change a tabId after it was set");
+ }
+ this.tabId = tabId;
+ }
+ if (windowId !== undefined) {
+ // Window IDs may change if a tab is moved to a different location.
+ // Note: This is the ID of the browser window for the extension API.
+ // Do not confuse it with the innerWindowID of DOMWindows!
+ this.windowId = windowId;
+ }
+ this.initialized = true;
+ }
+
+ // "DOMContentLoaded" event.
+ handleEvent(event) {
+ let {document} = this.global.content;
+ if (event.target === document) {
+ // If the document was still being loaded at the time of navigation, then
+ // the DOMContentLoaded event is fired for the old document. Ignore it.
+ if (this.initialDocuments.has(document)) {
+ this.initialDocuments.delete(document);
+ return;
+ }
+ this.global.removeEventListener("DOMContentLoaded", this);
+ this.global.sendAsyncMessage("Extension:ExtensionViewLoaded");
+ }
+ }
+}
+
+ExtensionChild = {
+ // Map<nsIContentFrameMessageManager, ContentGlobal>
+ contentGlobals: new Map(),
+
+ // Map<innerWindowId, ExtensionPageContextChild>
+ extensionContexts: new Map(),
+
+ initOnce() {
+ // This initializes the default message handler for messages targeted at
+ // an addon process, in case the addon process receives a message before
+ // its Messenger has been instantiated. For example, if a content script
+ // sends a message while there is no background page.
+ MessageChannel.setupMessageManagers([Services.cpmm]);
+ },
+
+ init(global) {
+ this.contentGlobals.set(global, new ContentGlobal(global));
+ },
+
+ uninit(global) {
+ this.contentGlobals.get(global).uninit();
+ this.contentGlobals.delete(global);
+ },
+
+ /**
+ * Create a privileged context at document-element-inserted.
+ *
+ * @param {BrowserExtensionContent} extension
+ * The extension for which the context should be created.
+ * @param {nsIDOMWindow} contentWindow The global of the page.
+ */
+ createExtensionContext(extension, contentWindow) {
+ let windowId = getInnerWindowID(contentWindow);
+ let context = this.extensionContexts.get(windowId);
+ if (context) {
+ if (context.extension !== extension) {
+ // Oops. This should never happen.
+ Cu.reportError("A different extension context already exists in this frame!");
+ } else {
+ // This should not happen either.
+ Cu.reportError("The extension context was already initialized in this frame.");
+ }
+ return;
+ }
+
+ let mm = contentWindow
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell)
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIContentFrameMessageManager);
+ let {viewType, tabId} = this.contentGlobals.get(mm).ensureInitialized();
+
+ let uri = contentWindow.document.documentURIObject;
+
+ context = new ExtensionPageContextChild(extension, {viewType, contentWindow, uri, tabId});
+ this.extensionContexts.set(windowId, context);
+ },
+
+ /**
+ * Close the ExtensionPageContextChild belonging to the given window, if any.
+ *
+ * @param {number} windowId The inner window ID of the destroyed context.
+ */
+ destroyExtensionContext(windowId) {
+ let context = this.extensionContexts.get(windowId);
+ if (context) {
+ context.unload();
+ this.extensionContexts.delete(windowId);
+ }
+ },
+
+ shutdownExtension(extensionId) {
+ for (let [windowId, context] of this.extensionContexts) {
+ if (context.extension.id == extensionId) {
+ context.shutdown();
+ this.extensionContexts.delete(windowId);
+ }
+ }
+ },
+};
+
+// TODO(robwu): Change this condition when addons move to a separate process.
+if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) {
+ Object.keys(ExtensionChild).forEach(function(key) {
+ if (typeof ExtensionChild[key] == "function") {
+ // :/
+ ExtensionChild[key] = () => {};
+ }
+ });
+}
+
+Object.assign(ExtensionChild, {
+ ChildAPIManager,
+ Messenger,
+ Port,
+});
+
diff --git a/toolkit/components/webextensions/ExtensionCommon.jsm b/toolkit/components/webextensions/ExtensionCommon.jsm
new file mode 100644
index 000000000..a339fb27e
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionCommon.jsm
@@ -0,0 +1,680 @@
+/* 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";
+
+/**
+ * This module contains utilities and base classes for logic which is
+ * common between the parent and child process, and in particular
+ * between ExtensionParent.jsm and ExtensionChild.jsm.
+ */
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+/* exported ExtensionCommon */
+
+this.EXPORTED_SYMBOLS = ["ExtensionCommon"];
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+var {
+ EventEmitter,
+ ExtensionError,
+ SpreadArgs,
+ getConsole,
+ getInnerWindowID,
+ getUniqueId,
+ runSafeSync,
+ runSafeSyncWithoutClone,
+ instanceOf,
+} = ExtensionUtils;
+
+XPCOMUtils.defineLazyGetter(this, "console", getConsole);
+
+class BaseContext {
+ constructor(envType, extension) {
+ this.envType = envType;
+ this.onClose = new Set();
+ this.checkedLastError = false;
+ this._lastError = null;
+ this.contextId = getUniqueId();
+ this.unloaded = false;
+ this.extension = extension;
+ this.jsonSandbox = null;
+ this.active = true;
+ this.incognito = null;
+ this.messageManager = null;
+ this.docShell = null;
+ this.contentWindow = null;
+ this.innerWindowID = 0;
+ }
+
+ setContentWindow(contentWindow) {
+ let {document} = contentWindow;
+ let docShell = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell);
+
+ this.innerWindowID = getInnerWindowID(contentWindow);
+ this.messageManager = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIContentFrameMessageManager);
+
+ if (this.incognito == null) {
+ this.incognito = PrivateBrowsingUtils.isContentWindowPrivate(contentWindow);
+ }
+
+ MessageChannel.setupMessageManagers([this.messageManager]);
+
+ let onPageShow = event => {
+ if (!event || event.target === document) {
+ this.docShell = docShell;
+ this.contentWindow = contentWindow;
+ this.active = true;
+ }
+ };
+ let onPageHide = event => {
+ if (!event || event.target === document) {
+ // Put this off until the next tick.
+ Promise.resolve().then(() => {
+ this.docShell = null;
+ this.contentWindow = null;
+ this.active = false;
+ });
+ }
+ };
+
+ onPageShow();
+ contentWindow.addEventListener("pagehide", onPageHide, true);
+ contentWindow.addEventListener("pageshow", onPageShow, true);
+ this.callOnClose({
+ close: () => {
+ onPageHide();
+ if (this.active) {
+ contentWindow.removeEventListener("pagehide", onPageHide, true);
+ contentWindow.removeEventListener("pageshow", onPageShow, true);
+ }
+ },
+ });
+ }
+
+ get cloneScope() {
+ throw new Error("Not implemented");
+ }
+
+ get principal() {
+ throw new Error("Not implemented");
+ }
+
+ runSafe(...args) {
+ if (this.unloaded) {
+ Cu.reportError("context.runSafe called after context unloaded");
+ } else if (!this.active) {
+ Cu.reportError("context.runSafe called while context is inactive");
+ } else {
+ return runSafeSync(this, ...args);
+ }
+ }
+
+ runSafeWithoutClone(...args) {
+ if (this.unloaded) {
+ Cu.reportError("context.runSafeWithoutClone called after context unloaded");
+ } else if (!this.active) {
+ Cu.reportError("context.runSafeWithoutClone called while context is inactive");
+ } else {
+ return runSafeSyncWithoutClone(...args);
+ }
+ }
+
+ checkLoadURL(url, options = {}) {
+ let ssm = Services.scriptSecurityManager;
+
+ let flags = ssm.STANDARD;
+ if (!options.allowScript) {
+ flags |= ssm.DISALLOW_SCRIPT;
+ }
+ if (!options.allowInheritsPrincipal) {
+ flags |= ssm.DISALLOW_INHERIT_PRINCIPAL;
+ }
+ if (options.dontReportErrors) {
+ flags |= ssm.DONT_REPORT_ERRORS;
+ }
+
+ try {
+ ssm.checkLoadURIStrWithPrincipal(this.principal, url, flags);
+ } catch (e) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Safely call JSON.stringify() on an object that comes from an
+ * extension.
+ *
+ * @param {array<any>} args Arguments for JSON.stringify()
+ * @returns {string} The stringified representation of obj
+ */
+ jsonStringify(...args) {
+ if (!this.jsonSandbox) {
+ this.jsonSandbox = Cu.Sandbox(this.principal, {
+ sameZoneAs: this.cloneScope,
+ wantXrays: false,
+ });
+ }
+
+ return Cu.waiveXrays(this.jsonSandbox.JSON).stringify(...args);
+ }
+
+ callOnClose(obj) {
+ this.onClose.add(obj);
+ }
+
+ forgetOnClose(obj) {
+ this.onClose.delete(obj);
+ }
+
+ /**
+ * A wrapper around MessageChannel.sendMessage which adds the extension ID
+ * to the recipient object, and ensures replies are not processed after the
+ * context has been unloaded.
+ *
+ * @param {nsIMessageManager} target
+ * @param {string} messageName
+ * @param {object} data
+ * @param {object} [options]
+ * @param {object} [options.sender]
+ * @param {object} [options.recipient]
+ *
+ * @returns {Promise}
+ */
+ sendMessage(target, messageName, data, options = {}) {
+ options.recipient = options.recipient || {};
+ options.sender = options.sender || {};
+
+ options.recipient.extensionId = this.extension.id;
+ options.sender.extensionId = this.extension.id;
+ options.sender.contextId = this.contextId;
+
+ return MessageChannel.sendMessage(target, messageName, data, options);
+ }
+
+ get lastError() {
+ this.checkedLastError = true;
+ return this._lastError;
+ }
+
+ set lastError(val) {
+ this.checkedLastError = false;
+ this._lastError = val;
+ }
+
+ /**
+ * Normalizes the given error object for use by the target scope. If
+ * the target is an error object which belongs to that scope, it is
+ * returned as-is. If it is an ordinary object with a `message`
+ * property, it is converted into an error belonging to the target
+ * scope. If it is an Error object which does *not* belong to the
+ * clone scope, it is reported, and converted to an unexpected
+ * exception error.
+ *
+ * @param {Error|object} error
+ * @returns {Error}
+ */
+ normalizeError(error) {
+ if (error instanceof this.cloneScope.Error) {
+ return error;
+ }
+ let message;
+ if (instanceOf(error, "Object") || error instanceof ExtensionError) {
+ message = error.message;
+ } else if (typeof error == "object" &&
+ this.principal.subsumes(Cu.getObjectPrincipal(error))) {
+ message = error.message;
+ } else {
+ Cu.reportError(error);
+ }
+ message = message || "An unexpected error occurred";
+ return new this.cloneScope.Error(message);
+ }
+
+ /**
+ * Sets the value of `.lastError` to `error`, calls the given
+ * callback, and reports an error if the value has not been checked
+ * when the callback returns.
+ *
+ * @param {object} error An object with a `message` property. May
+ * optionally be an `Error` object belonging to the target scope.
+ * @param {function} callback The callback to call.
+ * @returns {*} The return value of callback.
+ */
+ withLastError(error, callback) {
+ this.lastError = this.normalizeError(error);
+ try {
+ return callback();
+ } finally {
+ if (!this.checkedLastError) {
+ Cu.reportError(`Unchecked lastError value: ${this.lastError}`);
+ }
+ this.lastError = null;
+ }
+ }
+
+ /**
+ * Wraps the given promise so it can be safely returned to extension
+ * code in this context.
+ *
+ * If `callback` is provided, however, it is used as a completion
+ * function for the promise, and no promise is returned. In this case,
+ * the callback is called when the promise resolves or rejects. In the
+ * latter case, `lastError` is set to the rejection value, and the
+ * callback function must check `browser.runtime.lastError` or
+ * `extension.runtime.lastError` in order to prevent it being reported
+ * to the console.
+ *
+ * @param {Promise} promise The promise with which to wrap the
+ * callback. May resolve to a `SpreadArgs` instance, in which case
+ * each element will be used as a separate argument.
+ *
+ * Unless the promise object belongs to the cloneScope global, its
+ * resolution value is cloned into cloneScope prior to calling the
+ * `callback` function or resolving the wrapped promise.
+ *
+ * @param {function} [callback] The callback function to wrap
+ *
+ * @returns {Promise|undefined} If callback is null, a promise object
+ * belonging to the target scope. Otherwise, undefined.
+ */
+ wrapPromise(promise, callback = null) {
+ let runSafe = this.runSafe.bind(this);
+ if (promise instanceof this.cloneScope.Promise) {
+ runSafe = this.runSafeWithoutClone.bind(this);
+ }
+
+ if (callback) {
+ promise.then(
+ args => {
+ if (this.unloaded) {
+ dump(`Promise resolved after context unloaded\n`);
+ } else if (!this.active) {
+ dump(`Promise resolved while context is inactive\n`);
+ } else if (args instanceof SpreadArgs) {
+ runSafe(callback, ...args);
+ } else {
+ runSafe(callback, args);
+ }
+ },
+ error => {
+ this.withLastError(error, () => {
+ if (this.unloaded) {
+ dump(`Promise rejected after context unloaded\n`);
+ } else if (!this.active) {
+ dump(`Promise rejected while context is inactive\n`);
+ } else {
+ this.runSafeWithoutClone(callback);
+ }
+ });
+ });
+ } else {
+ return new this.cloneScope.Promise((resolve, reject) => {
+ promise.then(
+ value => {
+ if (this.unloaded) {
+ dump(`Promise resolved after context unloaded\n`);
+ } else if (!this.active) {
+ dump(`Promise resolved while context is inactive\n`);
+ } else if (value instanceof SpreadArgs) {
+ runSafe(resolve, value.length == 1 ? value[0] : value);
+ } else {
+ runSafe(resolve, value);
+ }
+ },
+ value => {
+ if (this.unloaded) {
+ dump(`Promise rejected after context unloaded: ${value && value.message}\n`);
+ } else if (!this.active) {
+ dump(`Promise rejected while context is inactive: ${value && value.message}\n`);
+ } else {
+ this.runSafeWithoutClone(reject, this.normalizeError(value));
+ }
+ });
+ });
+ }
+ }
+
+ unload() {
+ this.unloaded = true;
+
+ MessageChannel.abortResponses({
+ extensionId: this.extension.id,
+ contextId: this.contextId,
+ });
+
+ for (let obj of this.onClose) {
+ obj.close();
+ }
+ }
+
+ /**
+ * A simple proxy for unload(), for use with callOnClose().
+ */
+ close() {
+ this.unload();
+ }
+}
+
+/**
+ * An object that runs the implementation of a schema API. Instantiations of
+ * this interfaces are used by Schemas.jsm.
+ *
+ * @interface
+ */
+class SchemaAPIInterface {
+ /**
+ * Calls this as a function that returns its return value.
+ *
+ * @abstract
+ * @param {Array} args The parameters for the function.
+ * @returns {*} The return value of the invoked function.
+ */
+ callFunction(args) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Calls this as a function and ignores its return value.
+ *
+ * @abstract
+ * @param {Array} args The parameters for the function.
+ */
+ callFunctionNoReturn(args) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Calls this as a function that completes asynchronously.
+ *
+ * @abstract
+ * @param {Array} args The parameters for the function.
+ * @param {function(*)} [callback] The callback to be called when the function
+ * completes.
+ * @returns {Promise|undefined} Must be void if `callback` is set, and a
+ * promise otherwise. The promise is resolved when the function completes.
+ */
+ callAsyncFunction(args, callback) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Retrieves the value of this as a property.
+ *
+ * @abstract
+ * @returns {*} The value of the property.
+ */
+ getProperty() {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Assigns the value to this as property.
+ *
+ * @abstract
+ * @param {string} value The new value of the property.
+ */
+ setProperty(value) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Registers a `listener` to this as an event.
+ *
+ * @abstract
+ * @param {function} listener The callback to be called when the event fires.
+ * @param {Array} args Extra parameters for EventManager.addListener.
+ * @see EventManager.addListener
+ */
+ addListener(listener, args) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Checks whether `listener` is listening to this as an event.
+ *
+ * @abstract
+ * @param {function} listener The event listener.
+ * @returns {boolean} Whether `listener` is registered with this as an event.
+ * @see EventManager.hasListener
+ */
+ hasListener(listener) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Unregisters `listener` from this as an event.
+ *
+ * @abstract
+ * @param {function} listener The event listener.
+ * @see EventManager.removeListener
+ */
+ removeListener(listener) {
+ throw new Error("Not implemented");
+ }
+}
+
+/**
+ * An object that runs a locally implemented API.
+ */
+class LocalAPIImplementation extends SchemaAPIInterface {
+ /**
+ * Constructs an implementation of the `name` method or property of `pathObj`.
+ *
+ * @param {object} pathObj The object containing the member with name `name`.
+ * @param {string} name The name of the implemented member.
+ * @param {BaseContext} context The context in which the schema is injected.
+ */
+ constructor(pathObj, name, context) {
+ super();
+ this.pathObj = pathObj;
+ this.name = name;
+ this.context = context;
+ }
+
+ callFunction(args) {
+ return this.pathObj[this.name](...args);
+ }
+
+ callFunctionNoReturn(args) {
+ this.pathObj[this.name](...args);
+ }
+
+ callAsyncFunction(args, callback) {
+ let promise;
+ try {
+ promise = this.pathObj[this.name](...args) || Promise.resolve();
+ } catch (e) {
+ promise = Promise.reject(e);
+ }
+ return this.context.wrapPromise(promise, callback);
+ }
+
+ getProperty() {
+ return this.pathObj[this.name];
+ }
+
+ setProperty(value) {
+ this.pathObj[this.name] = value;
+ }
+
+ addListener(listener, args) {
+ try {
+ this.pathObj[this.name].addListener.call(null, listener, ...args);
+ } catch (e) {
+ throw this.context.normalizeError(e);
+ }
+ }
+
+ hasListener(listener) {
+ return this.pathObj[this.name].hasListener.call(null, listener);
+ }
+
+ removeListener(listener) {
+ this.pathObj[this.name].removeListener.call(null, listener);
+ }
+}
+
+/**
+ * This object loads the ext-*.js scripts that define the extension API.
+ *
+ * This class instance is shared with the scripts that it loads, so that the
+ * ext-*.js scripts and the instantiator can communicate with each other.
+ */
+class SchemaAPIManager extends EventEmitter {
+ /**
+ * @param {string} processType
+ * "main" - The main, one and only chrome browser process.
+ * "addon" - An addon process.
+ * "content" - A content process.
+ */
+ constructor(processType) {
+ super();
+ this.processType = processType;
+ this.global = this._createExtGlobal();
+ this._scriptScopes = [];
+ this._schemaApis = {
+ addon_parent: [],
+ addon_child: [],
+ content_parent: [],
+ content_child: [],
+ };
+ }
+
+ /**
+ * Create a global object that is used as the shared global for all ext-*.js
+ * scripts that are loaded via `loadScript`.
+ *
+ * @returns {object} A sandbox that is used as the global by `loadScript`.
+ */
+ _createExtGlobal() {
+ let global = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), {
+ wantXrays: false,
+ sandboxName: `Namespace of ext-*.js scripts for ${this.processType}`,
+ });
+
+ Object.assign(global, {global, Cc, Ci, Cu, Cr, XPCOMUtils, extensions: this});
+
+ XPCOMUtils.defineLazyGetter(global, "console", getConsole);
+
+ XPCOMUtils.defineLazyModuleGetter(global, "require",
+ "resource://devtools/shared/Loader.jsm");
+
+ return global;
+ }
+
+ /**
+ * Load an ext-*.js script. The script runs in its own scope, if it wishes to
+ * share state with another script it can assign to the `global` variable. If
+ * it wishes to communicate with this API manager, use `extensions`.
+ *
+ * @param {string} scriptUrl The URL of the ext-*.js script.
+ */
+ loadScript(scriptUrl) {
+ // Create the object in the context of the sandbox so that the script runs
+ // in the sandbox's context instead of here.
+ let scope = Cu.createObjectIn(this.global);
+
+ Services.scriptloader.loadSubScript(scriptUrl, scope, "UTF-8");
+
+ // Save the scope to avoid it being garbage collected.
+ this._scriptScopes.push(scope);
+ }
+
+ /**
+ * Called by an ext-*.js script to register an API.
+ *
+ * @param {string} namespace The API namespace.
+ * Intended to match the namespace of the generated API, but not used at
+ * the moment - see bugzil.la/1295774.
+ * @param {string} envType Restricts the API to contexts that run in the
+ * given environment. Must be one of the following:
+ * - "addon_parent" - addon APIs that runs in the main process.
+ * - "addon_child" - addon APIs that runs in an addon process.
+ * - "content_parent" - content script APIs that runs in the main process.
+ * - "content_child" - content script APIs that runs in a content process.
+ * @param {function(BaseContext)} getAPI A function that returns an object
+ * that will be merged with |chrome| and |browser|. The next example adds
+ * the create, update and remove methods to the tabs API.
+ *
+ * registerSchemaAPI("tabs", "addon_parent", (context) => ({
+ * tabs: { create, update },
+ * }));
+ * registerSchemaAPI("tabs", "addon_parent", (context) => ({
+ * tabs: { remove },
+ * }));
+ */
+ registerSchemaAPI(namespace, envType, getAPI) {
+ this._schemaApis[envType].push({namespace, getAPI});
+ }
+
+ /**
+ * Exports all registered scripts to `obj`.
+ *
+ * @param {BaseContext} context The context for which the API bindings are
+ * generated.
+ * @param {object} obj The destination of the API.
+ */
+ generateAPIs(context, obj) {
+ let apis = this._schemaApis[context.envType];
+ if (!apis) {
+ Cu.reportError(`No APIs have been registered for ${context.envType}`);
+ return;
+ }
+ SchemaAPIManager.generateAPIs(context, apis, obj);
+ }
+
+ /**
+ * Mash together all the APIs from `apis` into `obj`.
+ *
+ * @param {BaseContext} context The context for which the API bindings are
+ * generated.
+ * @param {Array} apis A list of objects, see `registerSchemaAPI`.
+ * @param {object} obj The destination of the API.
+ */
+ static generateAPIs(context, apis, obj) {
+ // Recursively copy properties from source to dest.
+ function copy(dest, source) {
+ for (let prop in source) {
+ let desc = Object.getOwnPropertyDescriptor(source, prop);
+ if (typeof(desc.value) == "object") {
+ if (!(prop in dest)) {
+ dest[prop] = {};
+ }
+ copy(dest[prop], source[prop]);
+ } else {
+ Object.defineProperty(dest, prop, desc);
+ }
+ }
+ }
+
+ for (let api of apis) {
+ if (Schemas.checkPermissions(api.namespace, context.extension)) {
+ api = api.getAPI(context);
+ copy(obj, api);
+ }
+ }
+ }
+}
+
+const ExtensionCommon = {
+ BaseContext,
+ LocalAPIImplementation,
+ SchemaAPIInterface,
+ SchemaAPIManager,
+};
diff --git a/toolkit/components/webextensions/ExtensionContent.jsm b/toolkit/components/webextensions/ExtensionContent.jsm
new file mode 100644
index 000000000..9b9a02091
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionContent.jsm
@@ -0,0 +1,1048 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionContent"];
+
+/* globals ExtensionContent */
+
+/*
+ * This file handles the content process side of extensions. It mainly
+ * takes care of content script injection, content script APIs, and
+ * messaging.
+ *
+ * This file is also the initial entry point for addon processes.
+ * ExtensionChild.jsm is responsible for functionality specific to addon
+ * processes.
+ */
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
+ "resource://gre/modules/ExtensionManagement.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "LanguageDetector",
+ "resource:///modules/translation/LanguageDetector.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MatchGlobs",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
+ "resource://gre/modules/PromiseUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "WebNavigationFrames",
+ "resource://gre/modules/WebNavigationFrames.jsm");
+
+Cu.import("resource://gre/modules/ExtensionChild.jsm");
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+const {
+ EventEmitter,
+ LocaleData,
+ defineLazyGetter,
+ flushJarCache,
+ getInnerWindowID,
+ promiseDocumentReady,
+ runSafeSyncWithoutClone,
+} = ExtensionUtils;
+
+const {
+ BaseContext,
+ SchemaAPIManager,
+} = ExtensionCommon;
+
+const {
+ ChildAPIManager,
+ Messenger,
+} = ExtensionChild;
+
+XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole);
+
+const CATEGORY_EXTENSION_SCRIPTS_CONTENT = "webextension-scripts-content";
+
+function isWhenBeforeOrSame(when1, when2) {
+ let table = {"document_start": 0,
+ "document_end": 1,
+ "document_idle": 2};
+ return table[when1] <= table[when2];
+}
+
+var apiManager = new class extends SchemaAPIManager {
+ constructor() {
+ super("content");
+ this.initialized = false;
+ }
+
+ generateAPIs(...args) {
+ if (!this.initialized) {
+ this.initialized = true;
+ for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS_CONTENT)) {
+ this.loadScript(value);
+ }
+ }
+ return super.generateAPIs(...args);
+ }
+
+ registerSchemaAPI(namespace, envType, getAPI) {
+ if (envType == "content_child") {
+ super.registerSchemaAPI(namespace, envType, getAPI);
+ }
+ }
+}();
+
+// Represents a content script.
+function Script(extension, options, deferred = PromiseUtils.defer()) {
+ this.extension = extension;
+ this.options = options;
+ this.run_at = this.options.run_at;
+ this.js = this.options.js || [];
+ this.css = this.options.css || [];
+ this.remove_css = this.options.remove_css;
+ this.match_about_blank = this.options.match_about_blank;
+
+ this.deferred = deferred;
+
+ this.matches_ = new MatchPattern(this.options.matches);
+ this.exclude_matches_ = new MatchPattern(this.options.exclude_matches || null);
+ // TODO: MatchPattern should pre-mangle host-only patterns so that we
+ // don't need to call a separate match function.
+ this.matches_host_ = new MatchPattern(this.options.matchesHost || null);
+ this.include_globs_ = new MatchGlobs(this.options.include_globs);
+ this.exclude_globs_ = new MatchGlobs(this.options.exclude_globs);
+
+ this.requiresCleanup = !this.remove_css && (this.css.length > 0 || options.cssCode);
+}
+
+Script.prototype = {
+ get cssURLs() {
+ // We can handle CSS urls (css) and CSS code (cssCode).
+ let urls = [];
+ for (let url of this.css) {
+ urls.push(this.extension.baseURI.resolve(url));
+ }
+
+ if (this.options.cssCode) {
+ let url = "data:text/css;charset=utf-8," + encodeURIComponent(this.options.cssCode);
+ urls.push(url);
+ }
+
+ return urls;
+ },
+
+ matches(window) {
+ let uri = window.document.documentURIObject;
+ let principal = window.document.nodePrincipal;
+
+ // If mozAddonManager is present on this page, don't allow
+ // content scripts.
+ if (window.navigator.mozAddonManager !== undefined) {
+ return false;
+ }
+
+ if (this.match_about_blank && ["about:blank", "about:srcdoc"].includes(uri.spec)) {
+ // When matching about:blank/srcdoc documents, the checks below
+ // need to be performed against the "owner" document's URI.
+ uri = principal.URI;
+ }
+
+ // Documents from data: URIs also inherit the principal.
+ if (Services.netUtils.URIChainHasFlags(uri, Ci.nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT)) {
+ if (!this.match_about_blank) {
+ return false;
+ }
+ uri = principal.URI;
+ }
+
+ if (!(this.matches_.matches(uri) || this.matches_host_.matchesIgnoringPath(uri))) {
+ return false;
+ }
+
+ if (this.exclude_matches_.matches(uri)) {
+ return false;
+ }
+
+ if (this.options.include_globs != null) {
+ if (!this.include_globs_.matches(uri.spec)) {
+ return false;
+ }
+ }
+
+ if (this.exclude_globs_.matches(uri.spec)) {
+ return false;
+ }
+
+ if (this.options.frame_id != null) {
+ if (WebNavigationFrames.getFrameId(window) != this.options.frame_id) {
+ return false;
+ }
+ } else if (!this.options.all_frames && window.top != window) {
+ return false;
+ }
+
+ return true;
+ },
+
+ cleanup(window) {
+ if (!this.remove_css) {
+ let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils);
+
+ for (let url of this.cssURLs) {
+ runSafeSyncWithoutClone(winUtils.removeSheetUsingURIString, url, winUtils.AUTHOR_SHEET);
+ }
+ }
+ },
+
+ /**
+ * Tries to inject this script into the given window and sandbox, if
+ * there are pending operations for the window's current load state.
+ *
+ * @param {Window} window
+ * The DOM Window to inject the scripts and CSS into.
+ * @param {Sandbox} sandbox
+ * A Sandbox inheriting from `window` in which to evaluate the
+ * injected scripts.
+ * @param {function} shouldRun
+ * A function which, when passed the document load state that a
+ * script is expected to run at, returns `true` if we should
+ * currently be injecting scripts for that load state.
+ *
+ * For initial injection of a script, this function should
+ * return true if the document is currently in or has already
+ * passed through the given state. For injections triggered by
+ * document state changes, it should only return true if the
+ * given state exactly matches the state that triggered the
+ * change.
+ * @param {string} when
+ * The document's current load state, or if triggered by a
+ * document state change, the new document state that triggered
+ * the injection.
+ */
+ tryInject(window, sandbox, shouldRun, when) {
+ if (shouldRun("document_start")) {
+ let {cssURLs} = this;
+ if (cssURLs.length > 0) {
+ let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils);
+
+ let method = this.remove_css ? winUtils.removeSheetUsingURIString : winUtils.loadSheetUsingURIString;
+ for (let url of cssURLs) {
+ runSafeSyncWithoutClone(method, url, winUtils.AUTHOR_SHEET);
+ }
+
+ this.deferred.resolve();
+ }
+ }
+
+ let result;
+ let scheduled = this.run_at || "document_idle";
+ if (shouldRun(scheduled)) {
+ for (let [i, url] of this.js.entries()) {
+ let options = {
+ target: sandbox,
+ charset: "UTF-8",
+ // Inject the last script asynchronously unless we're expected to
+ // inject before any page scripts have run, and we haven't already
+ // missed that boat.
+ async: (i === this.js.length - 1) &&
+ (this.run_at !== "document_start" || when !== "document_start"),
+ };
+ try {
+ result = Services.scriptloader.loadSubScriptWithOptions(url, options);
+ } catch (e) {
+ Cu.reportError(e);
+ this.deferred.reject(e);
+ }
+ }
+
+ if (this.options.jsCode) {
+ try {
+ result = Cu.evalInSandbox(this.options.jsCode, sandbox, "latest");
+ } catch (e) {
+ Cu.reportError(e);
+ this.deferred.reject(e);
+ }
+ }
+
+ this.deferred.resolve(result);
+ }
+ },
+};
+
+function getWindowMessageManager(contentWindow) {
+ let ir = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell)
+ .QueryInterface(Ci.nsIInterfaceRequestor);
+ try {
+ return ir.getInterface(Ci.nsIContentFrameMessageManager);
+ } catch (e) {
+ // Some windows don't support this interface (hidden window).
+ return null;
+ }
+}
+
+var DocumentManager;
+var ExtensionManager;
+
+/**
+ * An execution context for semi-privileged extension content scripts.
+ *
+ * This is the child side of the ContentScriptContextParent class
+ * defined in ExtensionParent.jsm.
+ */
+class ContentScriptContextChild extends BaseContext {
+ constructor(extension, contentWindow, contextOptions = {}) {
+ super("content_child", extension);
+
+ let {isExtensionPage} = contextOptions;
+
+ this.isExtensionPage = isExtensionPage;
+
+ this.setContentWindow(contentWindow);
+
+ let frameId = WebNavigationFrames.getFrameId(contentWindow);
+ this.frameId = frameId;
+
+ this.scripts = [];
+
+ let contentPrincipal = contentWindow.document.nodePrincipal;
+ let ssm = Services.scriptSecurityManager;
+
+ // copy origin attributes from the content window origin attributes to
+ // preserve the user context id. overwrite the addonId.
+ let attrs = contentPrincipal.originAttributes;
+ attrs.addonId = this.extension.id;
+ let extensionPrincipal = ssm.createCodebasePrincipal(this.extension.baseURI, attrs);
+
+ let principal;
+ if (ssm.isSystemPrincipal(contentPrincipal)) {
+ // Make sure we don't hand out the system principal by accident.
+ // also make sure that the null principal has the right origin attributes
+ principal = ssm.createNullPrincipal(attrs);
+ } else {
+ principal = [contentPrincipal, extensionPrincipal];
+ }
+
+ if (isExtensionPage) {
+ if (ExtensionManagement.getAddonIdForWindow(this.contentWindow) != this.extension.id) {
+ throw new Error("Invalid target window for this extension context");
+ }
+ // This is an iframe with content script API enabled and its principal should be the
+ // contentWindow itself. (we create a sandbox with the contentWindow as principal and with X-rays disabled
+ // because it enables us to create the APIs object in this sandbox object and then copying it
+ // into the iframe's window, see Bug 1214658 for rationale)
+ this.sandbox = Cu.Sandbox(contentWindow, {
+ sandboxPrototype: contentWindow,
+ sameZoneAs: contentWindow,
+ wantXrays: false,
+ isWebExtensionContentScript: true,
+ });
+ } else {
+ // This metadata is required by the Developer Tools, in order for
+ // the content script to be associated with both the extension and
+ // the tab holding the content page.
+ let metadata = {
+ "inner-window-id": this.innerWindowID,
+ addonId: attrs.addonId,
+ };
+
+ this.sandbox = Cu.Sandbox(principal, {
+ metadata,
+ sandboxPrototype: contentWindow,
+ sameZoneAs: contentWindow,
+ wantXrays: true,
+ isWebExtensionContentScript: true,
+ wantExportHelpers: true,
+ wantGlobalProperties: ["XMLHttpRequest", "fetch"],
+ originAttributes: attrs,
+ });
+
+ Cu.evalInSandbox(`
+ window.JSON = JSON;
+ window.XMLHttpRequest = XMLHttpRequest;
+ window.fetch = fetch;
+ `, this.sandbox);
+ }
+
+ Object.defineProperty(this, "principal", {
+ value: Cu.getObjectPrincipal(this.sandbox),
+ enumerable: true,
+ configurable: true,
+ });
+
+ this.url = contentWindow.location.href;
+
+ defineLazyGetter(this, "chromeObj", () => {
+ let chromeObj = Cu.createObjectIn(this.sandbox);
+
+ Schemas.inject(chromeObj, this.childManager);
+ return chromeObj;
+ });
+
+ Schemas.exportLazyGetter(this.sandbox, "browser", () => this.chromeObj);
+ Schemas.exportLazyGetter(this.sandbox, "chrome", () => this.chromeObj);
+
+ // This is an iframe with content script API enabled (bug 1214658)
+ if (isExtensionPage) {
+ Schemas.exportLazyGetter(this.contentWindow,
+ "browser", () => this.chromeObj);
+ Schemas.exportLazyGetter(this.contentWindow,
+ "chrome", () => this.chromeObj);
+ }
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+
+ execute(script, shouldRun, when) {
+ script.tryInject(this.contentWindow, this.sandbox, shouldRun, when);
+ }
+
+ addScript(script, when) {
+ let state = DocumentManager.getWindowState(this.contentWindow);
+ this.execute(script, scheduled => isWhenBeforeOrSame(scheduled, state), when);
+
+ // Save the script in case it has pending operations in later load
+ // states, but only if we're before document_idle, or require cleanup.
+ if (state != "document_idle" || script.requiresCleanup) {
+ this.scripts.push(script);
+ }
+ }
+
+ triggerScripts(documentState) {
+ for (let script of this.scripts) {
+ this.execute(script, scheduled => scheduled == documentState, documentState);
+ }
+ if (documentState == "document_idle") {
+ // Don't bother saving scripts after document_idle.
+ this.scripts = this.scripts.filter(script => script.requiresCleanup);
+ }
+ }
+
+ close() {
+ super.unload();
+
+ if (this.contentWindow) {
+ for (let script of this.scripts) {
+ if (script.requiresCleanup) {
+ script.cleanup(this.contentWindow);
+ }
+ }
+
+ // Overwrite the content script APIs with an empty object if the APIs objects are still
+ // defined in the content window (bug 1214658).
+ if (this.isExtensionPage) {
+ Cu.createObjectIn(this.contentWindow, {defineAs: "browser"});
+ Cu.createObjectIn(this.contentWindow, {defineAs: "chrome"});
+ }
+ }
+ Cu.nukeSandbox(this.sandbox);
+ this.sandbox = null;
+ }
+}
+
+defineLazyGetter(ContentScriptContextChild.prototype, "messenger", function() {
+ // The |sender| parameter is passed directly to the extension.
+ let sender = {id: this.extension.uuid, frameId: this.frameId, url: this.url};
+ let filter = {extensionId: this.extension.id};
+ let optionalFilter = {frameId: this.frameId};
+
+ return new Messenger(this, [this.messageManager], sender, filter, optionalFilter);
+});
+
+defineLazyGetter(ContentScriptContextChild.prototype, "childManager", function() {
+ let localApis = {};
+ apiManager.generateAPIs(this, localApis);
+
+ let childManager = new ChildAPIManager(this, this.messageManager, localApis, {
+ envType: "content_parent",
+ url: this.url,
+ });
+
+ this.callOnClose(childManager);
+
+ return childManager;
+});
+
+// Responsible for creating ExtensionContexts and injecting content
+// scripts into them when new documents are created.
+DocumentManager = {
+ extensionCount: 0,
+
+ // Map[windowId -> Map[extensionId -> ContentScriptContextChild]]
+ contentScriptWindows: new Map(),
+
+ // Map[windowId -> ContentScriptContextChild]
+ extensionPageWindows: new Map(),
+
+ init() {
+ Services.obs.addObserver(this, "content-document-global-created", false);
+ Services.obs.addObserver(this, "document-element-inserted", false);
+ Services.obs.addObserver(this, "inner-window-destroyed", false);
+ },
+
+ uninit() {
+ Services.obs.removeObserver(this, "content-document-global-created");
+ Services.obs.removeObserver(this, "document-element-inserted");
+ Services.obs.removeObserver(this, "inner-window-destroyed");
+ },
+
+ getWindowState(contentWindow) {
+ let readyState = contentWindow.document.readyState;
+ if (readyState == "complete") {
+ return "document_idle";
+ }
+ if (readyState == "interactive") {
+ return "document_end";
+ }
+ return "document_start";
+ },
+
+ loadInto(window) {
+ // Enable the content script APIs should be available in subframes' window
+ // if it is recognized as a valid addon id (see Bug 1214658 for rationale).
+ const {
+ NO_PRIVILEGES,
+ CONTENTSCRIPT_PRIVILEGES,
+ FULL_PRIVILEGES,
+ } = ExtensionManagement.API_LEVELS;
+ let extensionId = ExtensionManagement.getAddonIdForWindow(window);
+ let apiLevel = ExtensionManagement.getAPILevelForWindow(window, extensionId);
+
+ if (apiLevel != NO_PRIVILEGES) {
+ let extension = ExtensionManager.get(extensionId);
+ if (extension) {
+ if (apiLevel == CONTENTSCRIPT_PRIVILEGES) {
+ DocumentManager.getExtensionPageContext(extension, window);
+ } else if (apiLevel == FULL_PRIVILEGES) {
+ ExtensionChild.createExtensionContext(extension, window);
+ }
+ }
+ }
+ },
+
+ observe: function(subject, topic, data) {
+ // For some types of documents (about:blank), we only see the first
+ // notification, for others (data: URIs) we only observe the second.
+ if (topic == "content-document-global-created" || topic == "document-element-inserted") {
+ let document = subject;
+ let window = document && document.defaultView;
+
+ if (topic == "content-document-global-created") {
+ window = subject;
+ document = window && window.document;
+ }
+
+ if (!document || !document.location || !window) {
+ return;
+ }
+
+ // Make sure we only load into frames that ExtensionContent.init
+ // was called on (i.e., not frames for social or sidebars).
+ let mm = getWindowMessageManager(window);
+ if (!mm || !ExtensionContent.globals.has(mm)) {
+ return;
+ }
+
+ // Load on document-element-inserted, except for about:blank which doesn't
+ // see it, and needs special late handling on DOMContentLoaded event.
+ if (topic === "document-element-inserted") {
+ this.loadInto(window);
+ this.trigger("document_start", window);
+ }
+
+ /* eslint-disable mozilla/balanced-listeners */
+ window.addEventListener("DOMContentLoaded", this, true);
+ window.addEventListener("load", this, true);
+ /* eslint-enable mozilla/balanced-listeners */
+ } else if (topic == "inner-window-destroyed") {
+ let windowId = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
+
+ MessageChannel.abortResponses({innerWindowID: windowId});
+
+ // Close any existent content-script context for the destroyed window.
+ if (this.contentScriptWindows.has(windowId)) {
+ let extensions = this.contentScriptWindows.get(windowId);
+ for (let [, context] of extensions) {
+ context.close();
+ }
+
+ this.contentScriptWindows.delete(windowId);
+ }
+
+ // Close any existent iframe extension page context for the destroyed window.
+ if (this.extensionPageWindows.has(windowId)) {
+ let context = this.extensionPageWindows.get(windowId);
+ context.close();
+ this.extensionPageWindows.delete(windowId);
+ }
+
+ ExtensionChild.destroyExtensionContext(windowId);
+ }
+ },
+
+ handleEvent: function(event) {
+ let window = event.currentTarget;
+ if (event.target != window.document) {
+ // We use capturing listeners so we have precedence over content script
+ // listeners, but only care about events targeted to the element we're
+ // listening on.
+ return;
+ }
+ window.removeEventListener(event.type, this, true);
+
+ // Need to check if we're still on the right page? Greasemonkey does this.
+
+ if (event.type == "DOMContentLoaded") {
+ // By this time, we can be sure if this is an explicit about:blank
+ // document, and if it needs special late loading and fake trigger.
+ if (window.location.href === "about:blank") {
+ this.loadInto(window);
+ this.trigger("document_start", window);
+ }
+ this.trigger("document_end", window);
+ } else if (event.type == "load") {
+ this.trigger("document_idle", window);
+ }
+ },
+
+ // Used to executeScript, insertCSS and removeCSS.
+ executeScript(global, extensionId, options) {
+ let extension = ExtensionManager.get(extensionId);
+
+ let executeInWin = (window) => {
+ let deferred = PromiseUtils.defer();
+ let script = new Script(extension, options, deferred);
+
+ if (script.matches(window)) {
+ let context = this.getContentScriptContext(extension, window);
+ context.addScript(script);
+ return deferred.promise;
+ }
+ return null;
+ };
+
+ let promises = Array.from(this.enumerateWindows(global.docShell), executeInWin)
+ .filter(promise => promise);
+
+ if (!promises.length) {
+ let details = {};
+ for (let key of ["all_frames", "frame_id", "matches_about_blank", "matchesHost"]) {
+ if (key in options) {
+ details[key] = options[key];
+ }
+ }
+
+ return Promise.reject({message: `No window matching ${JSON.stringify(details)}`});
+ }
+ if (!options.all_frames && promises.length > 1) {
+ return Promise.reject({message: `Internal error: Script matched multiple windows`});
+ }
+ return Promise.all(promises);
+ },
+
+ enumerateWindows: function* (docShell) {
+ let window = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindow);
+ yield window;
+
+ for (let i = 0; i < docShell.childCount; i++) {
+ let child = docShell.getChildAt(i).QueryInterface(Ci.nsIDocShell);
+ yield* this.enumerateWindows(child);
+ }
+ },
+
+ getContentScriptGlobalsForWindow(window) {
+ let winId = getInnerWindowID(window);
+ let extensions = this.contentScriptWindows.get(winId);
+
+ if (extensions) {
+ return Array.from(extensions.values(), ctx => ctx.sandbox);
+ }
+
+ return [];
+ },
+
+ getContentScriptContext(extension, window) {
+ let winId = getInnerWindowID(window);
+ if (!this.contentScriptWindows.has(winId)) {
+ this.contentScriptWindows.set(winId, new Map());
+ }
+
+ let extensions = this.contentScriptWindows.get(winId);
+ if (!extensions.has(extension.id)) {
+ let context = new ContentScriptContextChild(extension, window);
+ extensions.set(extension.id, context);
+ }
+
+ return extensions.get(extension.id);
+ },
+
+ getExtensionPageContext(extension, window) {
+ let winId = getInnerWindowID(window);
+
+ let context = this.extensionPageWindows.get(winId);
+ if (!context) {
+ let context = new ContentScriptContextChild(extension, window, {isExtensionPage: true});
+ this.extensionPageWindows.set(winId, context);
+ }
+
+ return context;
+ },
+
+ startupExtension(extensionId) {
+ if (this.extensionCount == 0) {
+ this.init();
+ }
+ this.extensionCount++;
+
+ let extension = ExtensionManager.get(extensionId);
+ for (let global of ExtensionContent.globals.keys()) {
+ // Note that we miss windows in the bfcache here. In theory we
+ // could execute content scripts on a pageshow event for that
+ // window, but that seems extreme.
+ for (let window of this.enumerateWindows(global.docShell)) {
+ for (let script of extension.scripts) {
+ if (script.matches(window)) {
+ let context = this.getContentScriptContext(extension, window);
+ context.addScript(script);
+ }
+ }
+ }
+ }
+ },
+
+ shutdownExtension(extensionId) {
+ // Clean up content-script contexts on extension shutdown.
+ for (let [, extensions] of this.contentScriptWindows) {
+ let context = extensions.get(extensionId);
+ if (context) {
+ context.close();
+ extensions.delete(extensionId);
+ }
+ }
+
+ // Clean up iframe extension page contexts on extension shutdown.
+ for (let [winId, context] of this.extensionPageWindows) {
+ if (context.extension.id == extensionId) {
+ context.close();
+ this.extensionPageWindows.delete(winId);
+ }
+ }
+
+ ExtensionChild.shutdownExtension(extensionId);
+
+ MessageChannel.abortResponses({extensionId});
+
+ this.extensionCount--;
+ if (this.extensionCount == 0) {
+ this.uninit();
+ }
+ },
+
+ trigger(when, window) {
+ if (when === "document_start") {
+ for (let extension of ExtensionManager.extensions.values()) {
+ for (let script of extension.scripts) {
+ if (script.matches(window)) {
+ let context = this.getContentScriptContext(extension, window);
+ context.addScript(script, when);
+ }
+ }
+ }
+ } else {
+ let contexts = this.contentScriptWindows.get(getInnerWindowID(window)) || new Map();
+ for (let context of contexts.values()) {
+ context.triggerScripts(when);
+ }
+ }
+ },
+};
+
+// Represents a browser extension in the content process.
+class BrowserExtensionContent extends EventEmitter {
+ constructor(data) {
+ super();
+
+ this.id = data.id;
+ this.uuid = data.uuid;
+ this.data = data;
+ this.instanceId = data.instanceId;
+
+ this.MESSAGE_EMIT_EVENT = `Extension:EmitEvent:${this.instanceId}`;
+ Services.cpmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this);
+
+ this.scripts = data.content_scripts.map(scriptData => new Script(this, scriptData));
+ this.webAccessibleResources = new MatchGlobs(data.webAccessibleResources);
+ this.whiteListedHosts = new MatchPattern(data.whiteListedHosts);
+ this.permissions = data.permissions;
+ this.principal = data.principal;
+
+ this.localeData = new LocaleData(data.localeData);
+
+ this.manifest = data.manifest;
+ this.baseURI = Services.io.newURI(data.baseURL, null, null);
+
+ // Only used in addon processes.
+ this.views = new Set();
+
+ let uri = Services.io.newURI(data.resourceURL, null, null);
+
+ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ // Extension.jsm takes care of this in the parent.
+ ExtensionManagement.startupExtension(this.uuid, uri, this);
+ }
+ }
+
+ shutdown() {
+ Services.cpmm.removeMessageListener(this.MESSAGE_EMIT_EVENT, this);
+
+ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ ExtensionManagement.shutdownExtension(this.uuid);
+ }
+ }
+
+ emit(event, ...args) {
+ Services.cpmm.sendAsyncMessage(this.MESSAGE_EMIT_EVENT, {event, args});
+
+ super.emit(event, ...args);
+ }
+
+ receiveMessage({name, data}) {
+ if (name === this.MESSAGE_EMIT_EVENT) {
+ super.emit(data.event, ...data.args);
+ }
+ }
+
+ localizeMessage(...args) {
+ return this.localeData.localizeMessage(...args);
+ }
+
+ localize(...args) {
+ return this.localeData.localize(...args);
+ }
+
+ hasPermission(perm) {
+ let match = /^manifest:(.*)/.exec(perm);
+ if (match) {
+ return this.manifest[match[1]] != null;
+ }
+ return this.permissions.has(perm);
+ }
+}
+
+ExtensionManager = {
+ // Map[extensionId, BrowserExtensionContent]
+ extensions: new Map(),
+
+ init() {
+ Schemas.init();
+ ExtensionChild.initOnce();
+
+ Services.cpmm.addMessageListener("Extension:Startup", this);
+ Services.cpmm.addMessageListener("Extension:Shutdown", this);
+ Services.cpmm.addMessageListener("Extension:FlushJarCache", this);
+
+ if (Services.cpmm.initialProcessData && "Extension:Extensions" in Services.cpmm.initialProcessData) {
+ let extensions = Services.cpmm.initialProcessData["Extension:Extensions"];
+ for (let data of extensions) {
+ this.extensions.set(data.id, new BrowserExtensionContent(data));
+ DocumentManager.startupExtension(data.id);
+ }
+ }
+ },
+
+ get(extensionId) {
+ return this.extensions.get(extensionId);
+ },
+
+ receiveMessage({name, data}) {
+ let extension;
+ switch (name) {
+ case "Extension:Startup": {
+ extension = new BrowserExtensionContent(data);
+
+ this.extensions.set(data.id, extension);
+
+ DocumentManager.startupExtension(data.id);
+
+ Services.cpmm.sendAsyncMessage("Extension:StartupComplete");
+ break;
+ }
+
+ case "Extension:Shutdown": {
+ extension = this.extensions.get(data.id);
+ extension.shutdown();
+
+ DocumentManager.shutdownExtension(data.id);
+
+ this.extensions.delete(data.id);
+ break;
+ }
+
+ case "Extension:FlushJarCache": {
+ let nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile",
+ "initWithPath");
+ let file = new nsIFile(data.path);
+ flushJarCache(file);
+ Services.cpmm.sendAsyncMessage("Extension:FlushJarCacheComplete");
+ break;
+ }
+ }
+ },
+};
+
+class ExtensionGlobal {
+ constructor(global) {
+ this.global = global;
+
+ MessageChannel.addListener(global, "Extension:Capture", this);
+ MessageChannel.addListener(global, "Extension:DetectLanguage", this);
+ MessageChannel.addListener(global, "Extension:Execute", this);
+ MessageChannel.addListener(global, "WebNavigation:GetFrame", this);
+ MessageChannel.addListener(global, "WebNavigation:GetAllFrames", this);
+
+ this.windowId = global.content
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils)
+ .outerWindowID;
+
+ global.sendAsyncMessage("Extension:TopWindowID", {windowId: this.windowId});
+ }
+
+ uninit() {
+ this.global.sendAsyncMessage("Extension:RemoveTopWindowID", {windowId: this.windowId});
+ }
+
+ get messageFilterStrict() {
+ return {
+ innerWindowID: getInnerWindowID(this.global.content),
+ };
+ }
+
+ receiveMessage({target, messageName, recipient, data}) {
+ switch (messageName) {
+ case "Extension:Capture":
+ return this.handleExtensionCapture(data.width, data.height, data.options);
+ case "Extension:DetectLanguage":
+ return this.handleDetectLanguage(target);
+ case "Extension:Execute":
+ return this.handleExtensionExecute(target, recipient.extensionId, data.options);
+ case "WebNavigation:GetFrame":
+ return this.handleWebNavigationGetFrame(data.options);
+ case "WebNavigation:GetAllFrames":
+ return this.handleWebNavigationGetAllFrames();
+ }
+ }
+
+ handleExtensionCapture(width, height, options) {
+ let win = this.global.content;
+
+ const XHTML_NS = "http://www.w3.org/1999/xhtml";
+ let canvas = win.document.createElementNS(XHTML_NS, "canvas");
+ canvas.width = width;
+ canvas.height = height;
+ canvas.mozOpaque = true;
+
+ let ctx = canvas.getContext("2d");
+
+ // We need to scale the image to the visible size of the browser,
+ // in order for the result to appear as the user sees it when
+ // settings like full zoom come into play.
+ ctx.scale(canvas.width / win.innerWidth, canvas.height / win.innerHeight);
+
+ ctx.drawWindow(win, win.scrollX, win.scrollY, win.innerWidth, win.innerHeight, "#fff");
+
+ return canvas.toDataURL(`image/${options.format}`, options.quality / 100);
+ }
+
+ handleDetectLanguage(target) {
+ let doc = target.content.document;
+
+ return promiseDocumentReady(doc).then(() => {
+ let elem = doc.documentElement;
+
+ let language = (elem.getAttribute("xml:lang") || elem.getAttribute("lang") ||
+ doc.contentLanguage || null);
+
+ // We only want the last element of the TLD here.
+ // Only country codes have any effect on the results, but other
+ // values cause no harm.
+ let tld = doc.location.hostname.match(/[a-z]*$/)[0];
+
+ // The CLD2 library used by the language detector is capable of
+ // analyzing raw HTML. Unfortunately, that takes much more memory,
+ // and since it's hosted by emscripten, and therefore can't shrink
+ // its heap after it's grown, it has a performance cost.
+ // So we send plain text instead.
+ let encoder = Cc["@mozilla.org/layout/documentEncoder;1?type=text/plain"].createInstance(Ci.nsIDocumentEncoder);
+ encoder.init(doc, "text/plain", encoder.SkipInvisibleContent);
+ let text = encoder.encodeToStringWithMaxLength(60 * 1024);
+
+ let encoding = doc.characterSet;
+
+ return LanguageDetector.detectLanguage({language, tld, text, encoding})
+ .then(result => result.language === "un" ? "und" : result.language);
+ });
+ }
+
+ // Used to executeScript, insertCSS and removeCSS.
+ handleExtensionExecute(target, extensionId, options) {
+ return DocumentManager.executeScript(target, extensionId, options).then(result => {
+ try {
+ // Make sure we can structured-clone the result value before
+ // we try to send it back over the message manager.
+ Cu.cloneInto(result, target);
+ } catch (e) {
+ return Promise.reject({message: "Script returned non-structured-clonable data"});
+ }
+ return result;
+ });
+ }
+
+ handleWebNavigationGetFrame({frameId}) {
+ return WebNavigationFrames.getFrame(this.global.docShell, frameId);
+ }
+
+ handleWebNavigationGetAllFrames() {
+ return WebNavigationFrames.getAllFrames(this.global.docShell);
+ }
+}
+
+this.ExtensionContent = {
+ globals: new Map(),
+
+ init(global) {
+ this.globals.set(global, new ExtensionGlobal(global));
+ ExtensionChild.init(global);
+ },
+
+ uninit(global) {
+ ExtensionChild.uninit(global);
+ this.globals.get(global).uninit();
+ this.globals.delete(global);
+ },
+
+ // This helper is exported to be integrated in the devtools RDP actors,
+ // that can use it to retrieve the existent WebExtensions ContentScripts
+ // of a target window and be able to show the ContentScripts source in the
+ // DevTools Debugger panel.
+ getContentScriptGlobalsForWindow(window) {
+ return DocumentManager.getContentScriptGlobalsForWindow(window);
+ },
+};
+
+ExtensionManager.init();
diff --git a/toolkit/components/webextensions/ExtensionManagement.jsm b/toolkit/components/webextensions/ExtensionManagement.jsm
new file mode 100644
index 000000000..324c5b71b
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionManagement.jsm
@@ -0,0 +1,321 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionManagement"];
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import("resource://gre/modules/AppConstants.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils",
+ "resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "console", () => ExtensionUtils.getConsole());
+
+XPCOMUtils.defineLazyGetter(this, "UUIDMap", () => {
+ let {UUIDMap} = Cu.import("resource://gre/modules/Extension.jsm", {});
+ return UUIDMap;
+});
+
+/*
+ * This file should be kept short and simple since it's loaded even
+ * when no extensions are running.
+ */
+
+// Keep track of frame IDs for content windows. Mostly we can just use
+// the outer window ID as the frame ID. However, the API specifies
+// that top-level windows have a frame ID of 0. So we need to keep
+// track of which windows are top-level. This code listens to messages
+// from ExtensionContent to do that.
+var Frames = {
+ // Window IDs of top-level content windows.
+ topWindowIds: new Set(),
+
+ init() {
+ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ return;
+ }
+
+ Services.mm.addMessageListener("Extension:TopWindowID", this);
+ Services.mm.addMessageListener("Extension:RemoveTopWindowID", this, true);
+ },
+
+ isTopWindowId(windowId) {
+ return this.topWindowIds.has(windowId);
+ },
+
+ // Convert an outer window ID to a frame ID. An outer window ID of 0
+ // is invalid.
+ getId(windowId) {
+ if (this.isTopWindowId(windowId)) {
+ return 0;
+ }
+ if (windowId == 0) {
+ return -1;
+ }
+ return windowId;
+ },
+
+ // Convert an outer window ID for a parent window to a frame
+ // ID. Outer window IDs follow the same convention that
+ // |window.top.parent === window.top|. The API works differently,
+ // giving a frame ID of -1 for the the parent of a top-level
+ // window. This function handles the conversion.
+ getParentId(parentWindowId, windowId) {
+ if (parentWindowId == windowId) {
+ // We have a top-level window.
+ return -1;
+ }
+
+ // Not a top-level window. Just return the ID as normal.
+ return this.getId(parentWindowId);
+ },
+
+ receiveMessage({name, data}) {
+ switch (name) {
+ case "Extension:TopWindowID":
+ // FIXME: Need to handle the case where the content process
+ // crashes. Right now we leak its top window IDs.
+ this.topWindowIds.add(data.windowId);
+ break;
+
+ case "Extension:RemoveTopWindowID":
+ this.topWindowIds.delete(data.windowId);
+ break;
+ }
+ },
+};
+Frames.init();
+
+var APIs = {
+ apis: new Map(),
+
+ register(namespace, schema, script) {
+ if (this.apis.has(namespace)) {
+ throw new Error(`API namespace already exists: ${namespace}`);
+ }
+
+ this.apis.set(namespace, {schema, script});
+ },
+
+ unregister(namespace) {
+ if (!this.apis.has(namespace)) {
+ throw new Error(`API namespace does not exist: ${namespace}`);
+ }
+
+ this.apis.delete(namespace);
+ },
+};
+
+function getURLForExtension(id, path = "") {
+ let uuid = UUIDMap.get(id, false);
+ if (!uuid) {
+ Cu.reportError(`Called getURLForExtension on unmapped extension ${id}`);
+ return null;
+ }
+ return `moz-extension://${uuid}/${path}`;
+}
+
+// This object manages various platform-level issues related to
+// moz-extension:// URIs. It lives here so that it can be used in both
+// the parent and child processes.
+//
+// moz-extension URIs have the form moz-extension://uuid/path. Each
+// extension has its own UUID, unique to the machine it's installed
+// on. This is easier and more secure than using the extension ID,
+// since it makes it slightly harder to fingerprint for extensions if
+// each user uses different URIs for the extension.
+var Service = {
+ initialized: false,
+
+ // Map[uuid -> extension].
+ // extension can be an Extension (parent process) or BrowserExtensionContent (child process).
+ uuidMap: new Map(),
+
+ init() {
+ let aps = Cc["@mozilla.org/addons/policy-service;1"].getService(Ci.nsIAddonPolicyService);
+ aps = aps.wrappedJSObject;
+ this.aps = aps;
+ aps.setExtensionURILoadCallback(this.extensionURILoadableByAnyone.bind(this));
+ aps.setExtensionURIToAddonIdCallback(this.extensionURIToAddonID.bind(this));
+ },
+
+ // Called when a new extension is loaded.
+ startupExtension(uuid, uri, extension) {
+ if (!this.initialized) {
+ this.initialized = true;
+ this.init();
+ }
+
+ // Create the moz-extension://uuid mapping.
+ let handler = Services.io.getProtocolHandler("moz-extension");
+ handler.QueryInterface(Ci.nsISubstitutingProtocolHandler);
+ handler.setSubstitution(uuid, uri);
+
+ this.uuidMap.set(uuid, extension);
+ this.aps.setAddonHasPermissionCallback(extension.id, extension.hasPermission.bind(extension));
+ this.aps.setAddonLoadURICallback(extension.id, this.checkAddonMayLoad.bind(this, extension));
+ this.aps.setAddonLocalizeCallback(extension.id, extension.localize.bind(extension));
+ this.aps.setAddonCSP(extension.id, extension.manifest.content_security_policy);
+ this.aps.setBackgroundPageUrlCallback(uuid, this.generateBackgroundPageUrl.bind(this, extension));
+ },
+
+ // Called when an extension is unloaded.
+ shutdownExtension(uuid) {
+ let extension = this.uuidMap.get(uuid);
+ this.uuidMap.delete(uuid);
+ this.aps.setAddonHasPermissionCallback(extension.id, null);
+ this.aps.setAddonLoadURICallback(extension.id, null);
+ this.aps.setAddonLocalizeCallback(extension.id, null);
+ this.aps.setAddonCSP(extension.id, null);
+ this.aps.setBackgroundPageUrlCallback(uuid, null);
+
+ let handler = Services.io.getProtocolHandler("moz-extension");
+ handler.QueryInterface(Ci.nsISubstitutingProtocolHandler);
+ handler.setSubstitution(uuid, null);
+ },
+
+ // Return true if the given URI can be loaded from arbitrary web
+ // content. The manifest.json |web_accessible_resources| directive
+ // determines this.
+ extensionURILoadableByAnyone(uri) {
+ let uuid = uri.host;
+ let extension = this.uuidMap.get(uuid);
+ if (!extension || !extension.webAccessibleResources) {
+ return false;
+ }
+
+ let path = uri.QueryInterface(Ci.nsIURL).filePath;
+ if (path.length > 0 && path[0] == "/") {
+ path = path.substr(1);
+ }
+ return extension.webAccessibleResources.matches(path);
+ },
+
+ // Checks whether a given extension can load this URI (typically via
+ // an XML HTTP request). The manifest.json |permissions| directive
+ // determines this.
+ checkAddonMayLoad(extension, uri) {
+ return extension.whiteListedHosts.matchesIgnoringPath(uri);
+ },
+
+ generateBackgroundPageUrl(extension) {
+ let background_scripts = extension.manifest.background &&
+ extension.manifest.background.scripts;
+ if (!background_scripts) {
+ return;
+ }
+ let html = "<!DOCTYPE html>\n<body>\n";
+ for (let script of background_scripts) {
+ script = script.replace(/"/g, "&quot;");
+ html += `<script src="${script}"></script>\n`;
+ }
+ html += "</body>\n</html>\n";
+ return "data:text/html;charset=utf-8," + encodeURIComponent(html);
+ },
+
+ // Finds the add-on ID associated with a given moz-extension:// URI.
+ // This is used to set the addonId on the originAttributes for the
+ // nsIPrincipal attached to the URI.
+ extensionURIToAddonID(uri) {
+ let uuid = uri.host;
+ let extension = this.uuidMap.get(uuid);
+ return extension ? extension.id : undefined;
+ },
+};
+
+// API Levels Helpers
+
+// Find the add-on associated with this document via the
+// principal's originAttributes. This value is computed by
+// extensionURIToAddonID, which ensures that we don't inject our
+// API into webAccessibleResources or remote web pages.
+function getAddonIdForWindow(window) {
+ return Cu.getObjectPrincipal(window).originAttributes.addonId;
+}
+
+const API_LEVELS = Object.freeze({
+ NO_PRIVILEGES: 0,
+ CONTENTSCRIPT_PRIVILEGES: 1,
+ FULL_PRIVILEGES: 2,
+});
+
+// Finds the API Level ("FULL_PRIVILEGES", "CONTENTSCRIPT_PRIVILEGES", "NO_PRIVILEGES")
+// with a given a window object.
+function getAPILevelForWindow(window, addonId) {
+ const {NO_PRIVILEGES, CONTENTSCRIPT_PRIVILEGES, FULL_PRIVILEGES} = API_LEVELS;
+
+ // Non WebExtension URLs and WebExtension URLs from a different extension
+ // has no access to APIs.
+ if (!addonId || getAddonIdForWindow(window) != addonId) {
+ return NO_PRIVILEGES;
+ }
+
+ // Extension pages running in the content process always defaults to
+ // "content script API level privileges".
+ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ return CONTENTSCRIPT_PRIVILEGES;
+ }
+
+ let docShell = window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell);
+
+ // Handling of ExtensionPages running inside sub-frames.
+ if (docShell.sameTypeParent) {
+ let parentWindow = docShell.sameTypeParent.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindow);
+
+ // The option page iframe embedded in the about:addons tab should have
+ // full API level privileges. (see Bug 1256282 for rationale)
+ let parentDocument = parentWindow.document;
+ let parentIsSystemPrincipal = Services.scriptSecurityManager
+ .isSystemPrincipal(parentDocument.nodePrincipal);
+ if (parentDocument.location.href == "about:addons" && parentIsSystemPrincipal) {
+ return FULL_PRIVILEGES;
+ }
+
+ // The addon iframes embedded in a addon page from with the same addonId
+ // should have the same privileges of the sameTypeParent.
+ // (see Bug 1258347 for rationale)
+ let parentSameAddonPrivileges = getAPILevelForWindow(parentWindow, addonId);
+ if (parentSameAddonPrivileges > NO_PRIVILEGES) {
+ return parentSameAddonPrivileges;
+ }
+
+ // In all the other cases, WebExtension URLs loaded into sub-frame UI
+ // will have "content script API level privileges".
+ // (see Bug 1214658 for rationale)
+ return CONTENTSCRIPT_PRIVILEGES;
+ }
+
+ // WebExtension URLs loaded into top frames UI could have full API level privileges.
+ return FULL_PRIVILEGES;
+}
+
+this.ExtensionManagement = {
+ startupExtension: Service.startupExtension.bind(Service),
+ shutdownExtension: Service.shutdownExtension.bind(Service),
+
+ registerAPI: APIs.register.bind(APIs),
+ unregisterAPI: APIs.unregister.bind(APIs),
+
+ getFrameId: Frames.getId.bind(Frames),
+ getParentFrameId: Frames.getParentId.bind(Frames),
+
+ getURLForExtension,
+
+ // exported API Level Helpers
+ getAddonIdForWindow,
+ getAPILevelForWindow,
+ API_LEVELS,
+
+ APIs,
+};
diff --git a/toolkit/components/webextensions/ExtensionParent.jsm b/toolkit/components/webextensions/ExtensionParent.jsm
new file mode 100644
index 000000000..b88500d1e
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionParent.jsm
@@ -0,0 +1,551 @@
+/* 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";
+
+/**
+ * This module contains code for managing APIs that need to run in the
+ * parent process, and handles the parent side of operations that need
+ * to be proxied from ExtensionChild.jsm.
+ */
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+/* exported ExtensionParent */
+
+this.EXPORTED_SYMBOLS = ["ExtensionParent"];
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NativeApp",
+ "resource://gre/modules/NativeMessaging.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+var {
+ BaseContext,
+ SchemaAPIManager,
+} = ExtensionCommon;
+
+var {
+ MessageManagerProxy,
+ SpreadArgs,
+ defineLazyGetter,
+ findPathInObject,
+} = ExtensionUtils;
+
+const BASE_SCHEMA = "chrome://extensions/content/schemas/manifest.json";
+const CATEGORY_EXTENSION_SCHEMAS = "webextension-schemas";
+const CATEGORY_EXTENSION_SCRIPTS = "webextension-scripts";
+
+let schemaURLs = new Set();
+
+if (!AppConstants.RELEASE_OR_BETA) {
+ schemaURLs.add("chrome://extensions/content/schemas/experiments.json");
+}
+
+let GlobalManager;
+let ParentAPIManager;
+let ProxyMessenger;
+
+// This object loads the ext-*.js scripts that define the extension API.
+let apiManager = new class extends SchemaAPIManager {
+ constructor() {
+ super("main");
+ this.initialized = null;
+ }
+
+ // Loads all the ext-*.js scripts currently registered.
+ lazyInit() {
+ if (this.initialized) {
+ return this.initialized;
+ }
+
+ // Load order matters here. The base manifest defines types which are
+ // extended by other schemas, so needs to be loaded first.
+ let promise = Schemas.load(BASE_SCHEMA).then(() => {
+ let promises = [];
+ for (let [/* name */, url] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCHEMAS)) {
+ promises.push(Schemas.load(url));
+ }
+ for (let url of schemaURLs) {
+ promises.push(Schemas.load(url));
+ }
+ return Promise.all(promises);
+ });
+
+ for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS)) {
+ this.loadScript(value);
+ }
+
+ this.initialized = promise;
+ return this.initialized;
+ }
+
+ registerSchemaAPI(namespace, envType, getAPI) {
+ if (envType == "addon_parent" || envType == "content_parent") {
+ super.registerSchemaAPI(namespace, envType, getAPI);
+ }
+ }
+}();
+
+// Subscribes to messages related to the extension messaging API and forwards it
+// to the relevant message manager. The "sender" field for the `onMessage` and
+// `onConnect` events are updated if needed.
+ProxyMessenger = {
+ _initialized: false,
+ init() {
+ if (this._initialized) {
+ return;
+ }
+ this._initialized = true;
+
+ // TODO(robwu): When addons move to a separate process, we should use the
+ // parent process manager(s) of the addon process(es) instead of the
+ // in-process one.
+ let pipmm = Services.ppmm.getChildAt(0);
+ // Listen on the global frame message manager because content scripts send
+ // and receive extension messages via their frame.
+ // Listen on the parent process message manager because `runtime.connect`
+ // and `runtime.sendMessage` requests must be delivered to all frames in an
+ // addon process (by the API contract).
+ // And legacy addons are not associated with a frame, so that is another
+ // reason for having a parent process manager here.
+ let messageManagers = [Services.mm, pipmm];
+
+ MessageChannel.addListener(messageManagers, "Extension:Connect", this);
+ MessageChannel.addListener(messageManagers, "Extension:Message", this);
+ MessageChannel.addListener(messageManagers, "Extension:Port:Disconnect", this);
+ MessageChannel.addListener(messageManagers, "Extension:Port:PostMessage", this);
+ },
+
+ receiveMessage({target, messageName, channelId, sender, recipient, data, responseType}) {
+ if (recipient.toNativeApp) {
+ let {childId, toNativeApp} = recipient;
+ if (messageName == "Extension:Message") {
+ let context = ParentAPIManager.getContextById(childId);
+ return new NativeApp(context, toNativeApp).sendMessage(data);
+ }
+ if (messageName == "Extension:Connect") {
+ let context = ParentAPIManager.getContextById(childId);
+ NativeApp.onConnectNative(context, target.messageManager, data.portId, sender, toNativeApp);
+ return true;
+ }
+ // "Extension:Port:Disconnect" and "Extension:Port:PostMessage" for
+ // native messages are handled by NativeApp.
+ return;
+ }
+ let extension = GlobalManager.extensionMap.get(sender.extensionId);
+ let receiverMM = this._getMessageManagerForRecipient(recipient);
+ if (!extension || !receiverMM) {
+ return Promise.reject({
+ result: MessageChannel.RESULT_NO_HANDLER,
+ message: "No matching message handler for the given recipient.",
+ });
+ }
+
+ if ((messageName == "Extension:Message" ||
+ messageName == "Extension:Connect") &&
+ apiManager.global.tabGetSender) {
+ // From ext-tabs.js, undefined on Android.
+ apiManager.global.tabGetSender(extension, target, sender);
+ }
+ return MessageChannel.sendMessage(receiverMM, messageName, data, {
+ sender,
+ recipient,
+ responseType,
+ });
+ },
+
+ /**
+ * @param {object} recipient An object that was passed to
+ * `MessageChannel.sendMessage`.
+ * @returns {object|null} The message manager matching the recipient if found.
+ */
+ _getMessageManagerForRecipient(recipient) {
+ let {extensionId, tabId} = recipient;
+ // tabs.sendMessage / tabs.connect
+ if (tabId) {
+ // `tabId` being set implies that the tabs API is supported, so we don't
+ // need to check whether `TabManager` exists.
+ let tab = apiManager.global.TabManager.getTab(tabId, null, null);
+ return tab && tab.linkedBrowser.messageManager;
+ }
+
+ // runtime.sendMessage / runtime.connect
+ if (extensionId) {
+ // TODO(robwu): map the extensionId to the addon parent process's message
+ // manager when they run in a separate process.
+ return Services.ppmm.getChildAt(0);
+ }
+
+ return null;
+ },
+};
+
+// Responsible for loading extension APIs into the right globals.
+GlobalManager = {
+ // Map[extension ID -> Extension]. Determines which extension is
+ // responsible for content under a particular extension ID.
+ extensionMap: new Map(),
+ initialized: false,
+
+ init(extension) {
+ if (this.extensionMap.size == 0) {
+ ProxyMessenger.init();
+ apiManager.on("extension-browser-inserted", this._onExtensionBrowser);
+ this.initialized = true;
+ }
+
+ this.extensionMap.set(extension.id, extension);
+ },
+
+ uninit(extension) {
+ this.extensionMap.delete(extension.id);
+
+ if (this.extensionMap.size == 0 && this.initialized) {
+ apiManager.off("extension-browser-inserted", this._onExtensionBrowser);
+ this.initialized = false;
+ }
+ },
+
+ _onExtensionBrowser(type, browser) {
+ browser.messageManager.loadFrameScript(`data:,
+ Components.utils.import("resource://gre/modules/ExtensionContent.jsm");
+ ExtensionContent.init(this);
+ addEventListener("unload", function() {
+ ExtensionContent.uninit(this);
+ });
+ `, false);
+ },
+
+ getExtension(extensionId) {
+ return this.extensionMap.get(extensionId);
+ },
+
+ injectInObject(context, isChromeCompat, dest) {
+ apiManager.generateAPIs(context, dest);
+ SchemaAPIManager.generateAPIs(context, context.extension.apis, dest);
+ },
+};
+
+/**
+ * The proxied parent side of a context in ExtensionChild.jsm, for the
+ * parent side of a proxied API.
+ */
+class ProxyContextParent extends BaseContext {
+ constructor(envType, extension, params, xulBrowser, principal) {
+ super(envType, extension);
+
+ this.uri = NetUtil.newURI(params.url);
+
+ this.incognito = params.incognito;
+
+ // This message manager is used by ParentAPIManager to send messages and to
+ // close the ProxyContext if the underlying message manager closes. This
+ // message manager object may change when `xulBrowser` swaps docshells, e.g.
+ // when a tab is moved to a different window.
+ this.messageManagerProxy = new MessageManagerProxy(xulBrowser);
+
+ Object.defineProperty(this, "principal", {
+ value: principal, enumerable: true, configurable: true,
+ });
+
+ this.listenerProxies = new Map();
+
+ apiManager.emit("proxy-context-load", this);
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+
+ get xulBrowser() {
+ return this.messageManagerProxy.eventTarget;
+ }
+
+ get parentMessageManager() {
+ return this.messageManagerProxy.messageManager;
+ }
+
+ shutdown() {
+ this.unload();
+ }
+
+ unload() {
+ if (this.unloaded) {
+ return;
+ }
+ this.messageManagerProxy.dispose();
+ super.unload();
+ apiManager.emit("proxy-context-unload", this);
+ }
+}
+
+defineLazyGetter(ProxyContextParent.prototype, "apiObj", function() {
+ let obj = {};
+ GlobalManager.injectInObject(this, false, obj);
+ return obj;
+});
+
+defineLazyGetter(ProxyContextParent.prototype, "sandbox", function() {
+ return Cu.Sandbox(this.principal);
+});
+
+/**
+ * The parent side of proxied API context for extension content script
+ * running in ExtensionContent.jsm.
+ */
+class ContentScriptContextParent extends ProxyContextParent {
+}
+
+/**
+ * The parent side of proxied API context for extension page, such as a
+ * background script, a tab page, or a popup, running in
+ * ExtensionChild.jsm.
+ */
+class ExtensionPageContextParent extends ProxyContextParent {
+ constructor(envType, extension, params, xulBrowser) {
+ super(envType, extension, params, xulBrowser, extension.principal);
+
+ this.viewType = params.viewType;
+ }
+
+ // The window that contains this context. This may change due to moving tabs.
+ get xulWindow() {
+ return this.xulBrowser.ownerGlobal;
+ }
+
+ get windowId() {
+ if (!apiManager.global.WindowManager || this.viewType == "background") {
+ return;
+ }
+ // viewType popup or tab:
+ return apiManager.global.WindowManager.getId(this.xulWindow);
+ }
+
+ get tabId() {
+ if (!apiManager.global.TabManager) {
+ return; // Not yet supported on Android.
+ }
+ let {gBrowser} = this.xulBrowser.ownerGlobal;
+ let tab = gBrowser && gBrowser.getTabForBrowser(this.xulBrowser);
+ return tab && apiManager.global.TabManager.getId(tab);
+ }
+
+ onBrowserChange(browser) {
+ super.onBrowserChange(browser);
+ this.xulBrowser = browser;
+ }
+
+ shutdown() {
+ apiManager.emit("page-shutdown", this);
+ super.shutdown();
+ }
+}
+
+ParentAPIManager = {
+ proxyContexts: new Map(),
+
+ init() {
+ Services.obs.addObserver(this, "message-manager-close", false);
+
+ Services.mm.addMessageListener("API:CreateProxyContext", this);
+ Services.mm.addMessageListener("API:CloseProxyContext", this, true);
+ Services.mm.addMessageListener("API:Call", this);
+ Services.mm.addMessageListener("API:AddListener", this);
+ Services.mm.addMessageListener("API:RemoveListener", this);
+ },
+
+ observe(subject, topic, data) {
+ if (topic === "message-manager-close") {
+ let mm = subject;
+ for (let [childId, context] of this.proxyContexts) {
+ if (context.parentMessageManager === mm) {
+ this.closeProxyContext(childId);
+ }
+ }
+ }
+ },
+
+ shutdownExtension(extensionId) {
+ for (let [childId, context] of this.proxyContexts) {
+ if (context.extension.id == extensionId) {
+ context.shutdown();
+ this.proxyContexts.delete(childId);
+ }
+ }
+ },
+
+ receiveMessage({name, data, target}) {
+ switch (name) {
+ case "API:CreateProxyContext":
+ this.createProxyContext(data, target);
+ break;
+
+ case "API:CloseProxyContext":
+ this.closeProxyContext(data.childId);
+ break;
+
+ case "API:Call":
+ this.call(data, target);
+ break;
+
+ case "API:AddListener":
+ this.addListener(data, target);
+ break;
+
+ case "API:RemoveListener":
+ this.removeListener(data);
+ break;
+ }
+ },
+
+ createProxyContext(data, target) {
+ let {envType, extensionId, childId, principal} = data;
+ if (this.proxyContexts.has(childId)) {
+ throw new Error("A WebExtension context with the given ID already exists!");
+ }
+
+ let extension = GlobalManager.getExtension(extensionId);
+ if (!extension) {
+ throw new Error(`No WebExtension found with ID ${extensionId}`);
+ }
+
+ let context;
+ if (envType == "addon_parent") {
+ // Privileged addon contexts can only be loaded in documents whose main
+ // frame is also the same addon.
+ if (principal.URI.prePath !== extension.baseURI.prePath ||
+ !target.contentPrincipal.subsumes(principal)) {
+ throw new Error(`Refused to create privileged WebExtension context for ${principal.URI.spec}`);
+ }
+ context = new ExtensionPageContextParent(envType, extension, data, target);
+ } else if (envType == "content_parent") {
+ context = new ContentScriptContextParent(envType, extension, data, target, principal);
+ } else {
+ throw new Error(`Invalid WebExtension context envType: ${envType}`);
+ }
+ this.proxyContexts.set(childId, context);
+ },
+
+ closeProxyContext(childId) {
+ let context = this.proxyContexts.get(childId);
+ if (context) {
+ context.unload();
+ this.proxyContexts.delete(childId);
+ }
+ },
+
+ call(data, target) {
+ let context = this.getContextById(data.childId);
+ if (context.parentMessageManager !== target.messageManager) {
+ throw new Error("Got message on unexpected message manager");
+ }
+
+ let reply = result => {
+ if (!context.parentMessageManager) {
+ Cu.reportError("Cannot send function call result: other side closed connection");
+ return;
+ }
+
+ context.parentMessageManager.sendAsyncMessage(
+ "API:CallResult",
+ Object.assign({
+ childId: data.childId,
+ callId: data.callId,
+ }, result));
+ };
+
+ try {
+ let args = Cu.cloneInto(data.args, context.sandbox);
+ let result = findPathInObject(context.apiObj, data.path)(...args);
+
+ if (data.callId) {
+ result = result || Promise.resolve();
+
+ result.then(result => {
+ result = result instanceof SpreadArgs ? [...result] : [result];
+
+ reply({result});
+ }, error => {
+ error = context.normalizeError(error);
+ reply({error: {message: error.message}});
+ });
+ }
+ } catch (e) {
+ if (data.callId) {
+ let error = context.normalizeError(e);
+ reply({error: {message: error.message}});
+ } else {
+ Cu.reportError(e);
+ }
+ }
+ },
+
+ addListener(data, target) {
+ let context = this.getContextById(data.childId);
+ if (context.parentMessageManager !== target.messageManager) {
+ throw new Error("Got message on unexpected message manager");
+ }
+
+ let {childId} = data;
+
+ function listener(...listenerArgs) {
+ return context.sendMessage(
+ context.parentMessageManager,
+ "API:RunListener",
+ {
+ childId,
+ listenerId: data.listenerId,
+ path: data.path,
+ args: listenerArgs,
+ },
+ {
+ recipient: {childId},
+ });
+ }
+
+ context.listenerProxies.set(data.listenerId, listener);
+
+ let args = Cu.cloneInto(data.args, context.sandbox);
+ findPathInObject(context.apiObj, data.path).addListener(listener, ...args);
+ },
+
+ removeListener(data) {
+ let context = this.getContextById(data.childId);
+ let listener = context.listenerProxies.get(data.listenerId);
+ findPathInObject(context.apiObj, data.path).removeListener(listener);
+ },
+
+ getContextById(childId) {
+ let context = this.proxyContexts.get(childId);
+ if (!context) {
+ let error = new Error("WebExtension context not found!");
+ Cu.reportError(error);
+ throw error;
+ }
+ return context;
+ },
+};
+
+ParentAPIManager.init();
+
+
+const ExtensionParent = {
+ GlobalManager,
+ ParentAPIManager,
+ apiManager,
+};
diff --git a/toolkit/components/webextensions/ExtensionStorage.jsm b/toolkit/components/webextensions/ExtensionStorage.jsm
new file mode 100644
index 000000000..0b0ffb000
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionStorage.jsm
@@ -0,0 +1,241 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionStorage"];
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
+ "resource://gre/modules/AsyncShutdown.jsm");
+
+function jsonReplacer(key, value) {
+ switch (typeof(value)) {
+ // Serialize primitive types as-is.
+ case "string":
+ case "number":
+ case "boolean":
+ return value;
+
+ case "object":
+ if (value === null) {
+ return value;
+ }
+
+ switch (Cu.getClassName(value, true)) {
+ // Serialize arrays and ordinary objects as-is.
+ case "Array":
+ case "Object":
+ return value;
+
+ // Serialize Date objects and regular expressions as their
+ // string representations.
+ case "Date":
+ case "RegExp":
+ return String(value);
+ }
+ break;
+ }
+
+ if (!key) {
+ // If this is the root object, and we can't serialize it, serialize
+ // the value to an empty object.
+ return {};
+ }
+
+ // Everything else, omit entirely.
+ return undefined;
+}
+
+this.ExtensionStorage = {
+ cache: new Map(),
+ listeners: new Map(),
+
+ /**
+ * Sanitizes the given value, and returns a JSON-compatible
+ * representation of it, based on the privileges of the given global.
+ *
+ * @param {value} value
+ * The value to sanitize.
+ * @param {Context} context
+ * The extension context in which to sanitize the value
+ * @returns {value}
+ * The sanitized value.
+ */
+ sanitize(value, context) {
+ let json = context.jsonStringify(value, jsonReplacer);
+ return JSON.parse(json);
+ },
+
+ getExtensionDir(extensionId) {
+ return OS.Path.join(this.extensionDir, extensionId);
+ },
+
+ getStorageFile(extensionId) {
+ return OS.Path.join(this.extensionDir, extensionId, "storage.js");
+ },
+
+ read(extensionId) {
+ if (this.cache.has(extensionId)) {
+ return this.cache.get(extensionId);
+ }
+
+ let path = this.getStorageFile(extensionId);
+ let decoder = new TextDecoder();
+ let promise = OS.File.read(path);
+ promise = promise.then(array => {
+ return JSON.parse(decoder.decode(array));
+ }).catch((error) => {
+ if (!error.becauseNoSuchFile) {
+ Cu.reportError("Unable to parse JSON data for extension storage.");
+ }
+ return {};
+ });
+ this.cache.set(extensionId, promise);
+ return promise;
+ },
+
+ write(extensionId) {
+ let promise = this.read(extensionId).then(extData => {
+ let encoder = new TextEncoder();
+ let array = encoder.encode(JSON.stringify(extData));
+ let path = this.getStorageFile(extensionId);
+ OS.File.makeDir(this.getExtensionDir(extensionId), {
+ ignoreExisting: true,
+ from: OS.Constants.Path.profileDir,
+ });
+ let promise = OS.File.writeAtomic(path, array);
+ return promise;
+ }).catch(() => {
+ // Make sure this promise is never rejected.
+ Cu.reportError("Unable to write JSON data for extension storage.");
+ });
+
+ AsyncShutdown.profileBeforeChange.addBlocker(
+ "ExtensionStorage: Finish writing extension data",
+ promise);
+
+ return promise.then(() => {
+ AsyncShutdown.profileBeforeChange.removeBlocker(promise);
+ });
+ },
+
+ set(extensionId, items, context) {
+ return this.read(extensionId).then(extData => {
+ let changes = {};
+ for (let prop in items) {
+ let item = this.sanitize(items[prop], context);
+ changes[prop] = {oldValue: extData[prop], newValue: item};
+ extData[prop] = item;
+ }
+
+ this.notifyListeners(extensionId, changes);
+
+ return this.write(extensionId);
+ });
+ },
+
+ remove(extensionId, items) {
+ return this.read(extensionId).then(extData => {
+ let changes = {};
+ for (let prop of [].concat(items)) {
+ changes[prop] = {oldValue: extData[prop]};
+ delete extData[prop];
+ }
+
+ this.notifyListeners(extensionId, changes);
+
+ return this.write(extensionId);
+ });
+ },
+
+ clear(extensionId) {
+ return this.read(extensionId).then(extData => {
+ let changes = {};
+ for (let prop of Object.keys(extData)) {
+ changes[prop] = {oldValue: extData[prop]};
+ delete extData[prop];
+ }
+
+ this.notifyListeners(extensionId, changes);
+
+ return this.write(extensionId);
+ });
+ },
+
+ get(extensionId, keys) {
+ return this.read(extensionId).then(extData => {
+ let result = {};
+ if (keys === null) {
+ Object.assign(result, extData);
+ } else if (typeof(keys) == "object" && !Array.isArray(keys)) {
+ for (let prop in keys) {
+ if (prop in extData) {
+ result[prop] = extData[prop];
+ } else {
+ result[prop] = keys[prop];
+ }
+ }
+ } else {
+ for (let prop of [].concat(keys)) {
+ if (prop in extData) {
+ result[prop] = extData[prop];
+ }
+ }
+ }
+
+ return result;
+ });
+ },
+
+ addOnChangedListener(extensionId, listener) {
+ let listeners = this.listeners.get(extensionId) || new Set();
+ listeners.add(listener);
+ this.listeners.set(extensionId, listeners);
+ },
+
+ removeOnChangedListener(extensionId, listener) {
+ let listeners = this.listeners.get(extensionId);
+ listeners.delete(listener);
+ },
+
+ notifyListeners(extensionId, changes) {
+ let listeners = this.listeners.get(extensionId);
+ if (listeners) {
+ for (let listener of listeners) {
+ listener(changes);
+ }
+ }
+ },
+
+ init() {
+ if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) {
+ return;
+ }
+ Services.obs.addObserver(this, "extension-invalidate-storage-cache", false);
+ Services.obs.addObserver(this, "xpcom-shutdown", false);
+ },
+
+ observe(subject, topic, data) {
+ if (topic == "xpcom-shutdown") {
+ Services.obs.removeObserver(this, "extension-invalidate-storage-cache");
+ Services.obs.removeObserver(this, "xpcom-shutdown");
+ } else if (topic == "extension-invalidate-storage-cache") {
+ this.cache.clear();
+ }
+ },
+};
+
+XPCOMUtils.defineLazyGetter(ExtensionStorage, "extensionDir",
+ () => OS.Path.join(OS.Constants.Path.profileDir, "browser-extension-data"));
+
+ExtensionStorage.init();
diff --git a/toolkit/components/webextensions/ExtensionTestCommon.jsm b/toolkit/components/webextensions/ExtensionTestCommon.jsm
new file mode 100644
index 000000000..02453ddfd
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionTestCommon.jsm
@@ -0,0 +1,343 @@
+/* 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";
+
+/**
+ * This module contains extension testing helper logic which is common
+ * between all test suites.
+ */
+
+/* exported ExtensionTestCommon, MockExtension */
+
+this.EXPORTED_SYMBOLS = ["ExtensionTestCommon", "MockExtension"];
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.importGlobalProperties(["TextEncoder"]);
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Extension",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionParent",
+ "resource://gre/modules/ExtensionParent.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
+ "resource://gre/modules/FileUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "apiManager",
+ () => ExtensionParent.apiManager);
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "uuidGen",
+ "@mozilla.org/uuid-generator;1",
+ "nsIUUIDGenerator");
+
+const {
+ flushJarCache,
+ instanceOf,
+} = ExtensionUtils;
+
+XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole);
+
+
+/**
+ * A skeleton Extension-like object, used for testing, which installs an
+ * add-on via the add-on manager when startup() is called, and
+ * uninstalles it on shutdown().
+ *
+ * @param {string} id
+ * @param {nsIFile} file
+ * @param {nsIURI} rootURI
+ * @param {string} installType
+ */
+class MockExtension {
+ constructor(file, rootURI, installType) {
+ this.id = null;
+ this.file = file;
+ this.rootURI = rootURI;
+ this.installType = installType;
+ this.addon = null;
+
+ let promiseEvent = eventName => new Promise(resolve => {
+ let onstartup = (msg, extension) => {
+ if (this.addon && extension.id == this.addon.id) {
+ apiManager.off(eventName, onstartup);
+
+ this.id = extension.id;
+ this._extension = extension;
+ resolve(extension);
+ }
+ };
+ apiManager.on(eventName, onstartup);
+ });
+
+ this._extension = null;
+ this._extensionPromise = promiseEvent("startup");
+ this._readyPromise = promiseEvent("ready");
+ }
+
+ testMessage(...args) {
+ return this._extension.testMessage(...args);
+ }
+
+ on(...args) {
+ this._extensionPromise.then(extension => {
+ extension.on(...args);
+ });
+ }
+
+ off(...args) {
+ this._extensionPromise.then(extension => {
+ extension.off(...args);
+ });
+ }
+
+ startup() {
+ if (this.installType == "temporary") {
+ return AddonManager.installTemporaryAddon(this.file).then(addon => {
+ this.addon = addon;
+ return this._readyPromise;
+ });
+ } else if (this.installType == "permanent") {
+ return new Promise((resolve, reject) => {
+ AddonManager.getInstallForFile(this.file, install => {
+ let listener = {
+ onInstallFailed: reject,
+ onInstallEnded: (install, newAddon) => {
+ this.addon = newAddon;
+ resolve(this._readyPromise);
+ },
+ };
+
+ install.addListener(listener);
+ install.install();
+ });
+ });
+ }
+ throw new Error("installType must be one of: temporary, permanent");
+ }
+
+ shutdown() {
+ this.addon.uninstall();
+ return this.cleanupGeneratedFile();
+ }
+
+ cleanupGeneratedFile() {
+ flushJarCache(this.file);
+ return OS.File.remove(this.file.path);
+ }
+}
+
+class ExtensionTestCommon {
+ /**
+ * This code is designed to make it easy to test a WebExtension
+ * without creating a bunch of files. Everything is contained in a
+ * single JSON blob.
+ *
+ * Properties:
+ * "background": "<JS code>"
+ * A script to be loaded as the background script.
+ * The "background" section of the "manifest" property is overwritten
+ * if this is provided.
+ * "manifest": {...}
+ * Contents of manifest.json
+ * "files": {"filename1": "contents1", ...}
+ * Data to be included as files. Can be referenced from the manifest.
+ * If a manifest file is provided here, it takes precedence over
+ * a generated one. Always use "/" as a directory separator.
+ * Directories should appear here only implicitly (as a prefix
+ * to file names)
+ *
+ * To make things easier, the value of "background" and "files"[] can
+ * be a function, which is converted to source that is run.
+ *
+ * The generated extension is stored in the system temporary directory,
+ * and an nsIFile object pointing to it is returned.
+ *
+ * @param {object} data
+ * @returns {nsIFile}
+ */
+ static generateXPI(data) {
+ let manifest = data.manifest;
+ if (!manifest) {
+ manifest = {};
+ }
+
+ let files = data.files;
+ if (!files) {
+ files = {};
+ }
+
+ function provide(obj, keys, value, override = false) {
+ if (keys.length == 1) {
+ if (!(keys[0] in obj) || override) {
+ obj[keys[0]] = value;
+ }
+ } else {
+ if (!(keys[0] in obj)) {
+ obj[keys[0]] = {};
+ }
+ provide(obj[keys[0]], keys.slice(1), value, override);
+ }
+ }
+
+ provide(manifest, ["name"], "Generated extension");
+ provide(manifest, ["manifest_version"], 2);
+ provide(manifest, ["version"], "1.0");
+
+ if (data.background) {
+ let bgScript = uuidGen.generateUUID().number + ".js";
+
+ provide(manifest, ["background", "scripts"], [bgScript], true);
+ files[bgScript] = data.background;
+ }
+
+ provide(files, ["manifest.json"], manifest);
+
+ if (data.embedded) {
+ // Package this as a webextension embedded inside a legacy
+ // extension.
+
+ let xpiFiles = {
+ "install.rdf": `<?xml version="1.0" encoding="UTF-8"?>
+ <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+ <Description about="urn:mozilla:install-manifest"
+ em:id="${manifest.applications.gecko.id}"
+ em:name="${manifest.name}"
+ em:type="2"
+ em:version="${manifest.version}"
+ em:description=""
+ em:hasEmbeddedWebExtension="true"
+ em:bootstrap="true">
+
+ <!-- Firefox -->
+ <em:targetApplication>
+ <Description
+ em:id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"
+ em:minVersion="51.0a1"
+ em:maxVersion="*"/>
+ </em:targetApplication>
+ </Description>
+ </RDF>
+ `,
+
+ "bootstrap.js": `
+ function install() {}
+ function uninstall() {}
+ function shutdown() {}
+
+ function startup(data) {
+ data.webExtension.startup();
+ }
+ `,
+ };
+
+ for (let [path, data] of Object.entries(files)) {
+ xpiFiles[`webextension/${path}`] = data;
+ }
+
+ files = xpiFiles;
+ }
+
+ return this.generateZipFile(files);
+ }
+
+ static generateZipFile(files, baseName = "generated-extension.xpi") {
+ let ZipWriter = Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter");
+ let zipW = new ZipWriter();
+
+ let file = FileUtils.getFile("TmpD", [baseName]);
+ file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
+
+ const MODE_WRONLY = 0x02;
+ const MODE_TRUNCATE = 0x20;
+ zipW.open(file, MODE_WRONLY | MODE_TRUNCATE);
+
+ // Needs to be in microseconds for some reason.
+ let time = Date.now() * 1000;
+
+ function generateFile(filename) {
+ let components = filename.split("/");
+ let path = "";
+ for (let component of components.slice(0, -1)) {
+ path += component + "/";
+ if (!zipW.hasEntry(path)) {
+ zipW.addEntryDirectory(path, time, false);
+ }
+ }
+ }
+
+ for (let filename in files) {
+ let script = files[filename];
+ if (typeof(script) == "function") {
+ script = "(" + script.toString() + ")()";
+ } else if (instanceOf(script, "Object") || instanceOf(script, "Array")) {
+ script = JSON.stringify(script);
+ }
+
+ if (!instanceOf(script, "ArrayBuffer")) {
+ script = new TextEncoder("utf-8").encode(script).buffer;
+ }
+
+ let stream = Cc["@mozilla.org/io/arraybuffer-input-stream;1"].createInstance(Ci.nsIArrayBufferInputStream);
+ stream.setData(script, 0, script.byteLength);
+
+ generateFile(filename);
+ zipW.addEntryStream(filename, time, 0, stream, false);
+ }
+
+ zipW.close();
+
+ return file;
+ }
+
+ /**
+ * Generates a new extension using |Extension.generateXPI|, and initializes a
+ * new |Extension| instance which will execute it.
+ *
+ * @param {object} data
+ * @returns {Extension}
+ */
+ static generate(data) {
+ let file = this.generateXPI(data);
+
+ flushJarCache(file);
+ Services.ppmm.broadcastAsyncMessage("Extension:FlushJarCache", {path: file.path});
+
+ let fileURI = Services.io.newFileURI(file);
+ let jarURI = Services.io.newURI("jar:" + fileURI.spec + "!/", null, null);
+
+ // This may be "temporary" or "permanent".
+ if (data.useAddonManager) {
+ return new MockExtension(file, jarURI, data.useAddonManager);
+ }
+
+ let id;
+ if (data.manifest) {
+ if (data.manifest.applications && data.manifest.applications.gecko) {
+ id = data.manifest.applications.gecko.id;
+ } else if (data.manifest.browser_specific_settings && data.manifest.browser_specific_settings.gecko) {
+ id = data.manifest.browser_specific_settings.gecko.id;
+ }
+ }
+ if (!id) {
+ id = uuidGen.generateUUID().number;
+ }
+
+ return new Extension({
+ id,
+ resourceURI: jarURI,
+ cleanupFile: file,
+ });
+ }
+}
diff --git a/toolkit/components/webextensions/ExtensionUtils.jsm b/toolkit/components/webextensions/ExtensionUtils.jsm
new file mode 100644
index 000000000..e7f768c07
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionUtils.jsm
@@ -0,0 +1,1215 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionUtils"];
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+const INTEGER = /^[1-9]\d*$/;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ConsoleAPI",
+ "resource://gre/modules/Console.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "LanguageDetector",
+ "resource:///modules/translation/LanguageDetector.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Locale",
+ "resource://gre/modules/Locale.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel",
+ "resource://gre/modules/MessageChannel.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Preferences",
+ "resource://gre/modules/Preferences.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService",
+ "@mozilla.org/content/style-sheet-service;1",
+ "nsIStyleSheetService");
+
+function getConsole() {
+ return new ConsoleAPI({
+ maxLogLevelPref: "extensions.webextensions.log.level",
+ prefix: "WebExtensions",
+ });
+}
+
+XPCOMUtils.defineLazyGetter(this, "console", getConsole);
+
+let nextId = 0;
+const {uniqueProcessID} = Services.appinfo;
+
+function getUniqueId() {
+ return `${nextId++}-${uniqueProcessID}`;
+}
+
+/**
+ * An Error subclass for which complete error messages are always passed
+ * to extensions, rather than being interpreted as an unknown error.
+ */
+class ExtensionError extends Error {}
+
+function filterStack(error) {
+ return String(error.stack).replace(/(^.*(Task\.jsm|Promise-backend\.js).*\n)+/gm, "<Promise Chain>\n");
+}
+
+// Run a function and report exceptions.
+function runSafeSyncWithoutClone(f, ...args) {
+ try {
+ return f(...args);
+ } catch (e) {
+ dump(`Extension error: ${e} ${e.fileName} ${e.lineNumber}\n[[Exception stack\n${filterStack(e)}Current stack\n${filterStack(Error())}]]\n`);
+ Cu.reportError(e);
+ }
+}
+
+// Run a function and report exceptions.
+function runSafeWithoutClone(f, ...args) {
+ if (typeof(f) != "function") {
+ dump(`Extension error: expected function\n${filterStack(Error())}`);
+ return;
+ }
+
+ Promise.resolve().then(() => {
+ runSafeSyncWithoutClone(f, ...args);
+ });
+}
+
+// Run a function, cloning arguments into context.cloneScope, and
+// report exceptions. |f| is expected to be in context.cloneScope.
+function runSafeSync(context, f, ...args) {
+ if (context.unloaded) {
+ Cu.reportError("runSafeSync called after context unloaded");
+ return;
+ }
+
+ try {
+ args = Cu.cloneInto(args, context.cloneScope);
+ } catch (e) {
+ Cu.reportError(e);
+ dump(`runSafe failure: cloning into ${context.cloneScope}: ${e}\n\n${filterStack(Error())}`);
+ }
+ return runSafeSyncWithoutClone(f, ...args);
+}
+
+// Run a function, cloning arguments into context.cloneScope, and
+// report exceptions. |f| is expected to be in context.cloneScope.
+function runSafe(context, f, ...args) {
+ try {
+ args = Cu.cloneInto(args, context.cloneScope);
+ } catch (e) {
+ Cu.reportError(e);
+ dump(`runSafe failure: cloning into ${context.cloneScope}: ${e}\n\n${filterStack(Error())}`);
+ }
+ if (context.unloaded) {
+ dump(`runSafe failure: context is already unloaded ${filterStack(new Error())}\n`);
+ return undefined;
+ }
+ return runSafeWithoutClone(f, ...args);
+}
+
+function getInnerWindowID(window) {
+ return window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils)
+ .currentInnerWindowID;
+}
+
+// Return true if the given value is an instance of the given
+// native type.
+function instanceOf(value, type) {
+ return {}.toString.call(value) == `[object ${type}]`;
+}
+
+// Extend the object |obj| with the property descriptors of each object in
+// |args|.
+function extend(obj, ...args) {
+ for (let arg of args) {
+ let props = [...Object.getOwnPropertyNames(arg),
+ ...Object.getOwnPropertySymbols(arg)];
+ for (let prop of props) {
+ let descriptor = Object.getOwnPropertyDescriptor(arg, prop);
+ Object.defineProperty(obj, prop, descriptor);
+ }
+ }
+
+ return obj;
+}
+
+/**
+ * Similar to a WeakMap, but creates a new key with the given
+ * constructor if one is not present.
+ */
+class DefaultWeakMap extends WeakMap {
+ constructor(defaultConstructor, init) {
+ super(init);
+ this.defaultConstructor = defaultConstructor;
+ }
+
+ get(key) {
+ if (!this.has(key)) {
+ this.set(key, this.defaultConstructor(key));
+ }
+ return super.get(key);
+ }
+}
+
+class DefaultMap extends Map {
+ constructor(defaultConstructor, init) {
+ super(init);
+ this.defaultConstructor = defaultConstructor;
+ }
+
+ get(key) {
+ if (!this.has(key)) {
+ this.set(key, this.defaultConstructor(key));
+ }
+ return super.get(key);
+ }
+}
+
+class SpreadArgs extends Array {
+ constructor(args) {
+ super();
+ this.push(...args);
+ }
+}
+
+// Manages icon details for toolbar buttons in the |pageAction| and
+// |browserAction| APIs.
+let IconDetails = {
+ // Normalizes the various acceptable input formats into an object
+ // with icon size as key and icon URL as value.
+ //
+ // If a context is specified (function is called from an extension):
+ // Throws an error if an invalid icon size was provided or the
+ // extension is not allowed to load the specified resources.
+ //
+ // If no context is specified, instead of throwing an error, this
+ // function simply logs a warning message.
+ normalize(details, extension, context = null) {
+ let result = {};
+
+ try {
+ if (details.imageData) {
+ let imageData = details.imageData;
+
+ if (typeof imageData == "string") {
+ imageData = {"19": imageData};
+ }
+
+ for (let size of Object.keys(imageData)) {
+ if (!INTEGER.test(size)) {
+ throw new ExtensionError(`Invalid icon size ${size}, must be an integer`);
+ }
+ result[size] = imageData[size];
+ }
+ }
+
+ if (details.path) {
+ let path = details.path;
+ if (typeof path != "object") {
+ path = {"19": path};
+ }
+
+ let baseURI = context ? context.uri : extension.baseURI;
+
+ for (let size of Object.keys(path)) {
+ if (!INTEGER.test(size)) {
+ throw new ExtensionError(`Invalid icon size ${size}, must be an integer`);
+ }
+
+ let url = baseURI.resolve(path[size]);
+
+ // The Chrome documentation specifies these parameters as
+ // relative paths. We currently accept absolute URLs as well,
+ // which means we need to check that the extension is allowed
+ // to load them. This will throw an error if it's not allowed.
+ try {
+ Services.scriptSecurityManager.checkLoadURIStrWithPrincipal(
+ extension.principal, url,
+ Services.scriptSecurityManager.DISALLOW_SCRIPT);
+ } catch (e) {
+ throw new ExtensionError(`Illegal URL ${url}`);
+ }
+
+ result[size] = url;
+ }
+ }
+ } catch (e) {
+ // Function is called from extension code, delegate error.
+ if (context) {
+ throw e;
+ }
+ // If there's no context, it's because we're handling this
+ // as a manifest directive. Log a warning rather than
+ // raising an error.
+ extension.manifestError(`Invalid icon data: ${e}`);
+ }
+
+ return result;
+ },
+
+ // Returns the appropriate icon URL for the given icons object and the
+ // screen resolution of the given window.
+ getPreferredIcon(icons, extension = null, size = 16) {
+ const DEFAULT = "chrome://browser/content/extension.svg";
+
+ let bestSize = null;
+ if (icons[size]) {
+ bestSize = size;
+ } else if (icons[2 * size]) {
+ bestSize = 2 * size;
+ } else {
+ let sizes = Object.keys(icons)
+ .map(key => parseInt(key, 10))
+ .sort((a, b) => a - b);
+
+ bestSize = sizes.find(candidate => candidate > size) || sizes.pop();
+ }
+
+ if (bestSize) {
+ return {size: bestSize, icon: icons[bestSize]};
+ }
+
+ return {size, icon: DEFAULT};
+ },
+
+ convertImageURLToDataURL(imageURL, contentWindow, browserWindow, size = 18) {
+ return new Promise((resolve, reject) => {
+ let image = new contentWindow.Image();
+ image.onload = function() {
+ let canvas = contentWindow.document.createElement("canvas");
+ let ctx = canvas.getContext("2d");
+ let dSize = size * browserWindow.devicePixelRatio;
+
+ // Scales the image while maintaing width to height ratio.
+ // If the width and height differ, the image is centered using the
+ // smaller of the two dimensions.
+ let dWidth, dHeight, dx, dy;
+ if (this.width > this.height) {
+ dWidth = dSize;
+ dHeight = image.height * (dSize / image.width);
+ dx = 0;
+ dy = (dSize - dHeight) / 2;
+ } else {
+ dWidth = image.width * (dSize / image.height);
+ dHeight = dSize;
+ dx = (dSize - dWidth) / 2;
+ dy = 0;
+ }
+
+ ctx.drawImage(this, 0, 0, this.width, this.height, dx, dy, dWidth, dHeight);
+ resolve(canvas.toDataURL("image/png"));
+ };
+ image.onerror = reject;
+ image.src = imageURL;
+ });
+ },
+};
+
+const LISTENERS = Symbol("listeners");
+
+class EventEmitter {
+ constructor() {
+ this[LISTENERS] = new Map();
+ }
+
+ /**
+ * Adds the given function as a listener for the given event.
+ *
+ * The listener function may optionally return a Promise which
+ * resolves when it has completed all operations which event
+ * dispatchers may need to block on.
+ *
+ * @param {string} event
+ * The name of the event to listen for.
+ * @param {function(string, ...any)} listener
+ * The listener to call when events are emitted.
+ */
+ on(event, listener) {
+ if (!this[LISTENERS].has(event)) {
+ this[LISTENERS].set(event, new Set());
+ }
+
+ this[LISTENERS].get(event).add(listener);
+ }
+
+ /**
+ * Removes the given function as a listener for the given event.
+ *
+ * @param {string} event
+ * The name of the event to stop listening for.
+ * @param {function(string, ...any)} listener
+ * The listener function to remove.
+ */
+ off(event, listener) {
+ if (this[LISTENERS].has(event)) {
+ let set = this[LISTENERS].get(event);
+
+ set.delete(listener);
+ if (!set.size) {
+ this[LISTENERS].delete(event);
+ }
+ }
+ }
+
+ /**
+ * Triggers all listeners for the given event, and returns a promise
+ * which resolves when all listeners have been called, and any
+ * promises they have returned have likewise resolved.
+ *
+ * @param {string} event
+ * The name of the event to emit.
+ * @param {any} args
+ * Arbitrary arguments to pass to the listener functions, after
+ * the event name.
+ * @returns {Promise}
+ */
+ emit(event, ...args) {
+ let listeners = this[LISTENERS].get(event) || new Set();
+
+ let promises = Array.from(listeners, listener => {
+ return runSafeSyncWithoutClone(listener, event, ...args);
+ });
+
+ return Promise.all(promises);
+ }
+}
+
+function LocaleData(data) {
+ this.defaultLocale = data.defaultLocale;
+ this.selectedLocale = data.selectedLocale;
+ this.locales = data.locales || new Map();
+ this.warnedMissingKeys = new Set();
+
+ // Map(locale-name -> Map(message-key -> localized-string))
+ //
+ // Contains a key for each loaded locale, each of which is a
+ // Map of message keys to their localized strings.
+ this.messages = data.messages || new Map();
+
+ if (data.builtinMessages) {
+ this.messages.set(this.BUILTIN, data.builtinMessages);
+ }
+}
+
+
+LocaleData.prototype = {
+ // Representation of the object to send to content processes. This
+ // should include anything the content process might need.
+ serialize() {
+ return {
+ defaultLocale: this.defaultLocale,
+ selectedLocale: this.selectedLocale,
+ messages: this.messages,
+ locales: this.locales,
+ };
+ },
+
+ BUILTIN: "@@BUILTIN_MESSAGES",
+
+ has(locale) {
+ return this.messages.has(locale);
+ },
+
+ // https://developer.chrome.com/extensions/i18n
+ localizeMessage(message, substitutions = [], options = {}) {
+ let defaultOptions = {
+ locale: this.selectedLocale,
+ defaultValue: "",
+ cloneScope: null,
+ };
+
+ options = Object.assign(defaultOptions, options);
+
+ let locales = new Set([this.BUILTIN, options.locale, this.defaultLocale]
+ .filter(locale => this.messages.has(locale)));
+
+ // Message names are case-insensitive, so normalize them to lower-case.
+ message = message.toLowerCase();
+ for (let locale of locales) {
+ let messages = this.messages.get(locale);
+ if (messages.has(message)) {
+ let str = messages.get(message);
+
+ if (!Array.isArray(substitutions)) {
+ substitutions = [substitutions];
+ }
+
+ let replacer = (matched, index, dollarSigns) => {
+ if (index) {
+ // This is not quite Chrome-compatible. Chrome consumes any number
+ // of digits following the $, but only accepts 9 substitutions. We
+ // accept any number of substitutions.
+ index = parseInt(index, 10) - 1;
+ return index in substitutions ? substitutions[index] : "";
+ }
+ // For any series of contiguous `$`s, the first is dropped, and
+ // the rest remain in the output string.
+ return dollarSigns;
+ };
+ return str.replace(/\$(?:([1-9]\d*)|(\$+))/g, replacer);
+ }
+ }
+
+ // Check for certain pre-defined messages.
+ if (message == "@@ui_locale") {
+ return this.uiLocale;
+ } else if (message.startsWith("@@bidi_")) {
+ let registry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry);
+ let rtl = registry.isLocaleRTL("global");
+
+ if (message == "@@bidi_dir") {
+ return rtl ? "rtl" : "ltr";
+ } else if (message == "@@bidi_reversed_dir") {
+ return rtl ? "ltr" : "rtl";
+ } else if (message == "@@bidi_start_edge") {
+ return rtl ? "right" : "left";
+ } else if (message == "@@bidi_end_edge") {
+ return rtl ? "left" : "right";
+ }
+ }
+
+ if (!this.warnedMissingKeys.has(message)) {
+ let error = `Unknown localization message ${message}`;
+ if (options.cloneScope) {
+ error = new options.cloneScope.Error(error);
+ }
+ Cu.reportError(error);
+ this.warnedMissingKeys.add(message);
+ }
+ return options.defaultValue;
+ },
+
+ // Localize a string, replacing all |__MSG_(.*)__| tokens with the
+ // matching string from the current locale, as determined by
+ // |this.selectedLocale|.
+ //
+ // This may not be called before calling either |initLocale| or
+ // |initAllLocales|.
+ localize(str, locale = this.selectedLocale) {
+ if (!str) {
+ return str;
+ }
+
+ return str.replace(/__MSG_([A-Za-z0-9@_]+?)__/g, (matched, message) => {
+ return this.localizeMessage(message, [], {locale, defaultValue: matched});
+ });
+ },
+
+ // Validates the contents of a locale JSON file, normalizes the
+ // messages into a Map of message key -> localized string pairs.
+ addLocale(locale, messages, extension) {
+ let result = new Map();
+
+ // Chrome does not document the semantics of its localization
+ // system very well. It handles replacements by pre-processing
+ // messages, replacing |$[a-zA-Z0-9@_]+$| tokens with the value of their
+ // replacements. Later, it processes the resulting string for
+ // |$[0-9]| replacements.
+ //
+ // Again, it does not document this, but it accepts any number
+ // of sequential |$|s, and replaces them with that number minus
+ // 1. It also accepts |$| followed by any number of sequential
+ // digits, but refuses to process a localized string which
+ // provides more than 9 substitutions.
+ if (!instanceOf(messages, "Object")) {
+ extension.packagingError(`Invalid locale data for ${locale}`);
+ return result;
+ }
+
+ for (let key of Object.keys(messages)) {
+ let msg = messages[key];
+
+ if (!instanceOf(msg, "Object") || typeof(msg.message) != "string") {
+ extension.packagingError(`Invalid locale message data for ${locale}, message ${JSON.stringify(key)}`);
+ continue;
+ }
+
+ // Substitutions are case-insensitive, so normalize all of their names
+ // to lower-case.
+ let placeholders = new Map();
+ if (instanceOf(msg.placeholders, "Object")) {
+ for (let key of Object.keys(msg.placeholders)) {
+ placeholders.set(key.toLowerCase(), msg.placeholders[key]);
+ }
+ }
+
+ let replacer = (match, name) => {
+ let replacement = placeholders.get(name.toLowerCase());
+ if (instanceOf(replacement, "Object") && "content" in replacement) {
+ return replacement.content;
+ }
+ return "";
+ };
+
+ let value = msg.message.replace(/\$([A-Za-z0-9@_]+)\$/g, replacer);
+
+ // Message names are also case-insensitive, so normalize them to lower-case.
+ result.set(key.toLowerCase(), value);
+ }
+
+ this.messages.set(locale, result);
+ return result;
+ },
+
+ get acceptLanguages() {
+ let result = Preferences.get("intl.accept_languages", "", Ci.nsIPrefLocalizedString);
+ return result.split(/\s*,\s*/g);
+ },
+
+
+ get uiLocale() {
+ // Return the browser locale, but convert it to a Chrome-style
+ // locale code.
+ return Locale.getLocale().replace(/-/g, "_");
+ },
+};
+
+// This is a generic class for managing event listeners. Example usage:
+//
+// new EventManager(context, "api.subAPI", fire => {
+// let listener = (...) => {
+// // Fire any listeners registered with addListener.
+// fire(arg1, arg2);
+// };
+// // Register the listener.
+// SomehowRegisterListener(listener);
+// return () => {
+// // Return a way to unregister the listener.
+// SomehowUnregisterListener(listener);
+// };
+// }).api()
+//
+// The result is an object with addListener, removeListener, and
+// hasListener methods. |context| is an add-on scope (either an
+// ExtensionContext in the chrome process or ExtensionContext in a
+// content process). |name| is for debugging. |register| is a function
+// to register the listener. |register| is only called once, even if
+// multiple listeners are registered. |register| should return an
+// unregister function that will unregister the listener.
+function EventManager(context, name, register) {
+ this.context = context;
+ this.name = name;
+ this.register = register;
+ this.unregister = null;
+ this.callbacks = new Set();
+}
+
+EventManager.prototype = {
+ addListener(callback) {
+ if (typeof(callback) != "function") {
+ dump(`Expected function\n${Error().stack}`);
+ return;
+ }
+ if (this.context.unloaded) {
+ dump(`Cannot add listener to ${this.name} after context unloaded`);
+ return;
+ }
+
+ if (!this.callbacks.size) {
+ this.context.callOnClose(this);
+
+ let fireFunc = this.fire.bind(this);
+ let fireWithoutClone = this.fireWithoutClone.bind(this);
+ fireFunc.withoutClone = fireWithoutClone;
+ this.unregister = this.register(fireFunc);
+ }
+ this.callbacks.add(callback);
+ },
+
+ removeListener(callback) {
+ if (!this.callbacks.size) {
+ return;
+ }
+
+ this.callbacks.delete(callback);
+ if (this.callbacks.size == 0) {
+ this.unregister();
+ this.unregister = null;
+
+ this.context.forgetOnClose(this);
+ }
+ },
+
+ hasListener(callback) {
+ return this.callbacks.has(callback);
+ },
+
+ fire(...args) {
+ this._fireCommon("runSafe", args);
+ },
+
+ fireWithoutClone(...args) {
+ this._fireCommon("runSafeWithoutClone", args);
+ },
+
+ _fireCommon(runSafeMethod, args) {
+ for (let callback of this.callbacks) {
+ Promise.resolve(callback).then(callback => {
+ if (this.context.unloaded) {
+ dump(`${this.name} event fired after context unloaded.\n`);
+ } else if (!this.context.active) {
+ dump(`${this.name} event fired while context is inactive.\n`);
+ } else if (this.callbacks.has(callback)) {
+ this.context[runSafeMethod](callback, ...args);
+ }
+ });
+ }
+ },
+
+ close() {
+ if (this.callbacks.size) {
+ this.unregister();
+ }
+ this.callbacks.clear();
+ this.register = null;
+ this.unregister = null;
+ },
+
+ api() {
+ return {
+ addListener: callback => this.addListener(callback),
+ removeListener: callback => this.removeListener(callback),
+ hasListener: callback => this.hasListener(callback),
+ };
+ },
+};
+
+// Similar to EventManager, but it doesn't try to consolidate event
+// notifications. Each addListener call causes us to register once. It
+// allows extra arguments to be passed to addListener.
+function SingletonEventManager(context, name, register) {
+ this.context = context;
+ this.name = name;
+ this.register = register;
+ this.unregister = new Map();
+}
+
+SingletonEventManager.prototype = {
+ addListener(callback, ...args) {
+ let wrappedCallback = (...args) => {
+ if (this.context.unloaded) {
+ dump(`${this.name} event fired after context unloaded.\n`);
+ } else if (this.unregister.has(callback)) {
+ return callback(...args);
+ }
+ };
+
+ let unregister = this.register(wrappedCallback, ...args);
+ this.unregister.set(callback, unregister);
+ this.context.callOnClose(this);
+ },
+
+ removeListener(callback) {
+ if (!this.unregister.has(callback)) {
+ return;
+ }
+
+ let unregister = this.unregister.get(callback);
+ this.unregister.delete(callback);
+ unregister();
+ },
+
+ hasListener(callback) {
+ return this.unregister.has(callback);
+ },
+
+ close() {
+ for (let unregister of this.unregister.values()) {
+ unregister();
+ }
+ },
+
+ api() {
+ return {
+ addListener: (...args) => this.addListener(...args),
+ removeListener: (...args) => this.removeListener(...args),
+ hasListener: (...args) => this.hasListener(...args),
+ };
+ },
+};
+
+// Simple API for event listeners where events never fire.
+function ignoreEvent(context, name) {
+ return {
+ addListener: function(callback) {
+ let id = context.extension.id;
+ let frame = Components.stack.caller;
+ let msg = `In add-on ${id}, attempting to use listener "${name}", which is unimplemented.`;
+ let scriptError = Cc["@mozilla.org/scripterror;1"]
+ .createInstance(Ci.nsIScriptError);
+ scriptError.init(msg, frame.filename, null, frame.lineNumber,
+ frame.columnNumber, Ci.nsIScriptError.warningFlag,
+ "content javascript");
+ let consoleService = Cc["@mozilla.org/consoleservice;1"]
+ .getService(Ci.nsIConsoleService);
+ consoleService.logMessage(scriptError);
+ },
+ removeListener: function(callback) {},
+ hasListener: function(callback) {},
+ };
+}
+
+// Copy an API object from |source| into the scope |dest|.
+function injectAPI(source, dest) {
+ for (let prop in source) {
+ // Skip names prefixed with '_'.
+ if (prop[0] == "_") {
+ continue;
+ }
+
+ let desc = Object.getOwnPropertyDescriptor(source, prop);
+ if (typeof(desc.value) == "function") {
+ Cu.exportFunction(desc.value, dest, {defineAs: prop});
+ } else if (typeof(desc.value) == "object") {
+ let obj = Cu.createObjectIn(dest, {defineAs: prop});
+ injectAPI(desc.value, obj);
+ } else {
+ Object.defineProperty(dest, prop, desc);
+ }
+ }
+}
+
+/**
+ * Returns a Promise which resolves when the given document's DOM has
+ * fully loaded.
+ *
+ * @param {Document} doc The document to await the load of.
+ * @returns {Promise<Document>}
+ */
+function promiseDocumentReady(doc) {
+ if (doc.readyState == "interactive" || doc.readyState == "complete") {
+ return Promise.resolve(doc);
+ }
+
+ return new Promise(resolve => {
+ doc.addEventListener("DOMContentLoaded", function onReady(event) {
+ if (event.target === event.currentTarget) {
+ doc.removeEventListener("DOMContentLoaded", onReady, true);
+ resolve(doc);
+ }
+ }, true);
+ });
+}
+
+/**
+ * Returns a Promise which resolves when the given document is fully
+ * loaded.
+ *
+ * @param {Document} doc The document to await the load of.
+ * @returns {Promise<Document>}
+ */
+function promiseDocumentLoaded(doc) {
+ if (doc.readyState == "complete") {
+ return Promise.resolve(doc);
+ }
+
+ return new Promise(resolve => {
+ doc.defaultView.addEventListener("load", function onReady(event) {
+ doc.defaultView.removeEventListener("load", onReady);
+ resolve(doc);
+ });
+ });
+}
+
+/**
+ * Returns a Promise which resolves when the given event is dispatched to the
+ * given element.
+ *
+ * @param {Element} element
+ * The element on which to listen.
+ * @param {string} eventName
+ * The event to listen for.
+ * @param {boolean} [useCapture = true]
+ * If true, listen for the even in the capturing rather than
+ * bubbling phase.
+ * @param {Event} [test]
+ * An optional test function which, when called with the
+ * observer's subject and data, should return true if this is the
+ * expected event, false otherwise.
+ * @returns {Promise<Event>}
+ */
+function promiseEvent(element, eventName, useCapture = true, test = event => true) {
+ return new Promise(resolve => {
+ function listener(event) {
+ if (test(event)) {
+ element.removeEventListener(eventName, listener, useCapture);
+ resolve(event);
+ }
+ }
+ element.addEventListener(eventName, listener, useCapture);
+ });
+}
+
+/**
+ * Returns a Promise which resolves the given observer topic has been
+ * observed.
+ *
+ * @param {string} topic
+ * The topic to observe.
+ * @param {function(nsISupports, string)} [test]
+ * An optional test function which, when called with the
+ * observer's subject and data, should return true if this is the
+ * expected notification, false otherwise.
+ * @returns {Promise<object>}
+ */
+function promiseObserved(topic, test = () => true) {
+ return new Promise(resolve => {
+ let observer = (subject, topic, data) => {
+ if (test(subject, data)) {
+ Services.obs.removeObserver(observer, topic);
+ resolve({subject, data});
+ }
+ };
+ Services.obs.addObserver(observer, topic, false);
+ });
+}
+
+function getMessageManager(target) {
+ if (target instanceof Ci.nsIFrameLoaderOwner) {
+ return target.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader.messageManager;
+ }
+ return target.QueryInterface(Ci.nsIMessageSender);
+}
+
+function flushJarCache(jarFile) {
+ Services.obs.notifyObservers(jarFile, "flush-cache-entry", null);
+}
+
+const PlatformInfo = Object.freeze({
+ os: (function() {
+ let os = AppConstants.platform;
+ if (os == "macosx") {
+ os = "mac";
+ }
+ return os;
+ })(),
+ arch: (function() {
+ let abi = Services.appinfo.XPCOMABI;
+ let [arch] = abi.split("-");
+ if (arch == "x86") {
+ arch = "x86-32";
+ } else if (arch == "x86_64") {
+ arch = "x86-64";
+ }
+ return arch;
+ })(),
+});
+
+function detectLanguage(text) {
+ return LanguageDetector.detectLanguage(text).then(result => ({
+ isReliable: result.confident,
+ languages: result.languages.map(lang => {
+ return {
+ language: lang.languageCode,
+ percentage: lang.percent,
+ };
+ }),
+ }));
+}
+
+/**
+ * Convert any of several different representations of a date/time to a Date object.
+ * Accepts several formats:
+ * a Date object, an ISO8601 string, or a number of milliseconds since the epoch as
+ * either a number or a string.
+ *
+ * @param {Date|string|number} date
+ * The date to convert.
+ * @returns {Date}
+ * A Date object
+ */
+function normalizeTime(date) {
+ // Of all the formats we accept the "number of milliseconds since the epoch as a string"
+ // is an outlier, everything else can just be passed directly to the Date constructor.
+ return new Date((typeof date == "string" && /^\d+$/.test(date))
+ ? parseInt(date, 10) : date);
+}
+
+const stylesheetMap = new DefaultMap(url => {
+ let uri = NetUtil.newURI(url);
+ return styleSheetService.preloadSheet(uri, styleSheetService.AGENT_SHEET);
+});
+
+/**
+ * Defines a lazy getter for the given property on the given object. The
+ * first time the property is accessed, the return value of the getter
+ * is defined on the current `this` object with the given property name.
+ * Importantly, this means that a lazy getter defined on an object
+ * prototype will be invoked separately for each object instance that
+ * it's accessed on.
+ *
+ * @param {object} object
+ * The prototype object on which to define the getter.
+ * @param {string|Symbol} prop
+ * The property name for which to define the getter.
+ * @param {function} getter
+ * The function to call in order to generate the final property
+ * value.
+ */
+function defineLazyGetter(object, prop, getter) {
+ let redefine = (obj, value) => {
+ Object.defineProperty(obj, prop, {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value,
+ });
+ return value;
+ };
+
+ Object.defineProperty(object, prop, {
+ enumerable: true,
+ configurable: true,
+
+ get() {
+ return redefine(this, getter.call(this));
+ },
+
+ set(value) {
+ redefine(this, value);
+ },
+ });
+}
+
+function findPathInObject(obj, path, printErrors = true) {
+ let parent;
+ for (let elt of path.split(".")) {
+ if (!obj || !(elt in obj)) {
+ if (printErrors) {
+ Cu.reportError(`WebExtension API ${path} not found (it may be unimplemented by Firefox).`);
+ }
+ return null;
+ }
+
+ parent = obj;
+ obj = obj[elt];
+ }
+
+ if (typeof obj === "function") {
+ return obj.bind(parent);
+ }
+ return obj;
+}
+
+/**
+ * Acts as a proxy for a message manager or message manager owner, and
+ * tracks docShell swaps so that messages are always sent to the same
+ * receiver, even if it is moved to a different <browser>.
+ *
+ * @param {nsIMessageSender|Element} target
+ * The target message manager on which to send messages, or the
+ * <browser> element which owns it.
+ */
+class MessageManagerProxy {
+ constructor(target) {
+ this.listeners = new DefaultMap(() => new Map());
+
+ if (target instanceof Ci.nsIMessageSender) {
+ Object.defineProperty(this, "messageManager", {
+ value: target,
+ configurable: true,
+ writable: true,
+ });
+ } else {
+ this.addListeners(target);
+ }
+ }
+
+ /**
+ * Disposes of the proxy object, removes event listeners, and drops
+ * all references to the underlying message manager.
+ *
+ * Must be called before the last reference to the proxy is dropped,
+ * unless the underlying message manager or <browser> is also being
+ * destroyed.
+ */
+ dispose() {
+ if (this.eventTarget) {
+ this.removeListeners(this.eventTarget);
+ this.eventTarget = null;
+ } else {
+ this.messageManager = null;
+ }
+ }
+
+ /**
+ * Returns true if the given target is the same as, or owns, the given
+ * message manager.
+ *
+ * @param {nsIMessageSender|MessageManagerProxy|Element} target
+ * The message manager, MessageManagerProxy, or <browser>
+ * element agaisnt which to match.
+ * @param {nsIMessageSender} messageManager
+ * The message manager against which to match `target`.
+ *
+ * @returns {boolean}
+ * True if `messageManager` is the same object as `target`, or
+ * `target` is a MessageManagerProxy or <browser> element that
+ * is tied to it.
+ */
+ static matches(target, messageManager) {
+ return target === messageManager || target.messageManager === messageManager;
+ }
+
+ /**
+ * @property {nsIMessageSender|null} messageManager
+ * The message manager that is currently being proxied. This
+ * may change during the life of the proxy object, so should
+ * not be stored elsewhere.
+ */
+ get messageManager() {
+ return this.eventTarget && this.eventTarget.messageManager;
+ }
+
+ /**
+ * Sends a message on the proxied message manager.
+ *
+ * @param {array} args
+ * Arguments to be passed verbatim to the underlying
+ * sendAsyncMessage method.
+ * @returns {undefined}
+ */
+ sendAsyncMessage(...args) {
+ if (this.messageManager) {
+ return this.messageManager.sendAsyncMessage(...args);
+ }
+ /* globals uneval */
+ Cu.reportError(`Cannot send message: Other side disconnected: ${uneval(args)}`);
+ }
+
+ /**
+ * Adds a message listener to the current message manager, and
+ * transfers it to the new message manager after a docShell swap.
+ *
+ * @param {string} message
+ * The name of the message to listen for.
+ * @param {nsIMessageListener} listener
+ * The listener to add.
+ * @param {boolean} [listenWhenClosed = false]
+ * If true, the listener will receive messages which were sent
+ * after the remote side of the listener began closing.
+ */
+ addMessageListener(message, listener, listenWhenClosed = false) {
+ this.messageManager.addMessageListener(message, listener, listenWhenClosed);
+ this.listeners.get(message).set(listener, listenWhenClosed);
+ }
+
+ /**
+ * Adds a message listener from the current message manager.
+ *
+ * @param {string} message
+ * The name of the message to stop listening for.
+ * @param {nsIMessageListener} listener
+ * The listener to remove.
+ */
+ removeMessageListener(message, listener) {
+ this.messageManager.removeMessageListener(message, listener);
+
+ let listeners = this.listeners.get(message);
+ listeners.delete(listener);
+ if (!listeners.size) {
+ this.listeners.delete(message);
+ }
+ }
+
+ /**
+ * @private
+ * Iterates over all of the currently registered message listeners.
+ */
+ * iterListeners() {
+ for (let [message, listeners] of this.listeners) {
+ for (let [listener, listenWhenClosed] of listeners) {
+ yield {message, listener, listenWhenClosed};
+ }
+ }
+ }
+
+ /**
+ * @private
+ * Adds docShell swap listeners to the message manager owner.
+ *
+ * @param {Element} target
+ * The target element.
+ */
+ addListeners(target) {
+ target.addEventListener("SwapDocShells", this);
+
+ for (let {message, listener, listenWhenClosed} of this.iterListeners()) {
+ target.addMessageListener(message, listener, listenWhenClosed);
+ }
+
+ this.eventTarget = target;
+ }
+
+ /**
+ * @private
+ * Removes docShell swap listeners to the message manager owner.
+ *
+ * @param {Element} target
+ * The target element.
+ */
+ removeListeners(target) {
+ target.removeEventListener("SwapDocShells", this);
+
+ for (let {message, listener} of this.iterListeners()) {
+ target.removeMessageListener(message, listener);
+ }
+ }
+
+ handleEvent(event) {
+ if (event.type == "SwapDocShells") {
+ this.removeListeners(this.eventTarget);
+ this.addListeners(event.detail);
+ }
+ }
+}
+
+this.ExtensionUtils = {
+ defineLazyGetter,
+ detectLanguage,
+ extend,
+ findPathInObject,
+ flushJarCache,
+ getConsole,
+ getInnerWindowID,
+ getMessageManager,
+ getUniqueId,
+ ignoreEvent,
+ injectAPI,
+ instanceOf,
+ normalizeTime,
+ promiseDocumentLoaded,
+ promiseDocumentReady,
+ promiseEvent,
+ promiseObserved,
+ runSafe,
+ runSafeSync,
+ runSafeSyncWithoutClone,
+ runSafeWithoutClone,
+ stylesheetMap,
+ DefaultMap,
+ DefaultWeakMap,
+ EventEmitter,
+ EventManager,
+ ExtensionError,
+ IconDetails,
+ LocaleData,
+ MessageManagerProxy,
+ PlatformInfo,
+ SingletonEventManager,
+ SpreadArgs,
+};
diff --git a/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm b/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm
new file mode 100644
index 000000000..339709a19
--- /dev/null
+++ b/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm
@@ -0,0 +1,306 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["ExtensionTestUtils"];
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Components.utils.import("resource://gre/modules/Task.jsm");
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "Extension",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
+ "resource://gre/modules/FileUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "Management", () => {
+ const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {});
+ return Management;
+});
+
+/* exported ExtensionTestUtils */
+
+let BASE_MANIFEST = Object.freeze({
+ "applications": Object.freeze({
+ "gecko": Object.freeze({
+ "id": "test@web.ext",
+ }),
+ }),
+
+ "manifest_version": 2,
+
+ "name": "name",
+ "version": "0",
+});
+
+class ExtensionWrapper {
+ constructor(extension, testScope) {
+ this.extension = extension;
+ this.testScope = testScope;
+
+ this.state = "uninitialized";
+
+ this.testResolve = null;
+ this.testDone = new Promise(resolve => { this.testResolve = resolve; });
+
+ this.messageHandler = new Map();
+ this.messageAwaiter = new Map();
+
+ this.messageQueue = new Set();
+
+ this.attachListeners();
+
+ this.testScope.do_register_cleanup(() => {
+ if (this.messageQueue.size) {
+ let names = Array.from(this.messageQueue, ([msg]) => msg);
+ this.testScope.equal(JSON.stringify(names), "[]", "message queue is empty");
+ }
+ if (this.messageAwaiter.size) {
+ let names = Array.from(this.messageAwaiter.keys());
+ this.testScope.equal(JSON.stringify(names), "[]", "no tasks awaiting on messages");
+ }
+ });
+
+ this.testScope.do_register_cleanup(() => {
+ if (this.state == "pending" || this.state == "running") {
+ this.testScope.equal(this.state, "unloaded", "Extension left running at test shutdown");
+ return this.unload();
+ } else if (extension.state == "unloading") {
+ this.testScope.equal(this.state, "unloaded", "Extension not fully unloaded at test shutdown");
+ }
+ });
+
+ this.testScope.do_print(`Extension loaded`);
+ }
+
+ attachListeners() {
+ /* eslint-disable mozilla/balanced-listeners */
+ this.extension.on("test-eq", (kind, pass, msg, expected, actual) => {
+ this.testScope.ok(pass, `${msg} - Expected: ${expected}, Actual: ${actual}`);
+ });
+ this.extension.on("test-log", (kind, pass, msg) => {
+ this.testScope.do_print(msg);
+ });
+ this.extension.on("test-result", (kind, pass, msg) => {
+ this.testScope.ok(pass, msg);
+ });
+ this.extension.on("test-done", (kind, pass, msg, expected, actual) => {
+ this.testScope.ok(pass, msg);
+ this.testResolve(msg);
+ });
+
+ this.extension.on("test-message", (kind, msg, ...args) => {
+ let handler = this.messageHandler.get(msg);
+ if (handler) {
+ handler(...args);
+ } else {
+ this.messageQueue.add([msg, ...args]);
+ this.checkMessages();
+ }
+ });
+ /* eslint-enable mozilla/balanced-listeners */
+ }
+
+ startup() {
+ if (this.state != "uninitialized") {
+ throw new Error("Extension already started");
+ }
+ this.state = "pending";
+
+ return this.extension.startup().then(
+ result => {
+ this.state = "running";
+
+ return result;
+ },
+ error => {
+ this.state = "failed";
+
+ return Promise.reject(error);
+ });
+ }
+
+ unload() {
+ if (this.state != "running") {
+ throw new Error("Extension not running");
+ }
+ this.state = "unloading";
+
+ this.extension.shutdown();
+
+ this.state = "unloaded";
+
+ return Promise.resolve();
+ }
+
+ /*
+ * This method marks the extension unloading without actually calling
+ * shutdown, since shutting down a MockExtension causes it to be uninstalled.
+ *
+ * Normally you shouldn't need to use this unless you need to test something
+ * that requires a restart, such as updates.
+ */
+ markUnloaded() {
+ if (this.state != "running") {
+ throw new Error("Extension not running");
+ }
+ this.state = "unloaded";
+
+ return Promise.resolve();
+ }
+
+ sendMessage(...args) {
+ this.extension.testMessage(...args);
+ }
+
+ awaitFinish(msg) {
+ return this.testDone.then(actual => {
+ if (msg) {
+ this.testScope.equal(actual, msg, "test result correct");
+ }
+ return actual;
+ });
+ }
+
+ checkMessages() {
+ for (let message of this.messageQueue) {
+ let [msg, ...args] = message;
+
+ let listener = this.messageAwaiter.get(msg);
+ if (listener) {
+ this.messageQueue.delete(message);
+ this.messageAwaiter.delete(msg);
+
+ listener.resolve(...args);
+ return;
+ }
+ }
+ }
+
+ checkDuplicateListeners(msg) {
+ if (this.messageHandler.has(msg) || this.messageAwaiter.has(msg)) {
+ throw new Error("only one message handler allowed");
+ }
+ }
+
+ awaitMessage(msg) {
+ return new Promise(resolve => {
+ this.checkDuplicateListeners(msg);
+
+ this.messageAwaiter.set(msg, {resolve});
+ this.checkMessages();
+ });
+ }
+
+ onMessage(msg, callback) {
+ this.checkDuplicateListeners(msg);
+ this.messageHandler.set(msg, callback);
+ }
+}
+
+var ExtensionTestUtils = {
+ BASE_MANIFEST,
+
+ normalizeManifest: Task.async(function* (manifest, baseManifest = BASE_MANIFEST) {
+ yield Management.lazyInit();
+
+ let errors = [];
+ let context = {
+ url: null,
+
+ logError: error => {
+ errors.push(error);
+ },
+
+ preprocessors: {},
+ };
+
+ manifest = Object.assign({}, baseManifest, manifest);
+
+ let normalized = Schemas.normalize(manifest, "manifest.WebExtensionManifest", context);
+ normalized.errors = errors;
+
+ return normalized;
+ }),
+
+ currentScope: null,
+
+ profileDir: null,
+
+ init(scope) {
+ this.currentScope = scope;
+
+ this.profileDir = scope.do_get_profile();
+
+ // We need to load at least one frame script into every message
+ // manager to ensure that the scriptable wrapper for its global gets
+ // created before we try to access it externally. If we don't, we
+ // fail sanity checks on debug builds the first time we try to
+ // create a wrapper, because we should never have a global without a
+ // cached wrapper.
+ Services.mm.loadFrameScript("data:text/javascript,//", true);
+
+
+ let tmpD = this.profileDir.clone();
+ tmpD.append("tmp");
+ tmpD.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+ let dirProvider = {
+ getFile(prop, persistent) {
+ persistent.value = false;
+ if (prop == "TmpD") {
+ return tmpD.clone();
+ }
+ return null;
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider]),
+ };
+ Services.dirsvc.registerProvider(dirProvider);
+
+
+ scope.do_register_cleanup(() => {
+ tmpD.remove(true);
+ Services.dirsvc.unregisterProvider(dirProvider);
+
+ this.currentScope = null;
+ });
+ },
+
+ addonManagerStarted: false,
+
+ mockAppInfo() {
+ const {updateAppInfo} = Cu.import("resource://testing-common/AppInfo.jsm", {});
+ updateAppInfo({
+ ID: "xpcshell@tests.mozilla.org",
+ name: "XPCShell",
+ version: "48",
+ platformVersion: "48",
+ });
+ },
+
+ startAddonManager() {
+ if (this.addonManagerStarted) {
+ return;
+ }
+ this.addonManagerStarted = true;
+ this.mockAppInfo();
+
+ let manager = Cc["@mozilla.org/addons/integration;1"].getService(Ci.nsIObserver)
+ .QueryInterface(Ci.nsITimerCallback);
+ manager.observe(null, "addons-startup", null);
+ },
+
+ loadExtension(data) {
+ let extension = Extension.generate(data);
+
+ return new ExtensionWrapper(extension, this.currentScope);
+ },
+};
diff --git a/toolkit/components/webextensions/LegacyExtensionsUtils.jsm b/toolkit/components/webextensions/LegacyExtensionsUtils.jsm
new file mode 100644
index 000000000..7632548e3
--- /dev/null
+++ b/toolkit/components/webextensions/LegacyExtensionsUtils.jsm
@@ -0,0 +1,250 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["LegacyExtensionsUtils"];
+
+/* exported LegacyExtensionsUtils, LegacyExtensionContext */
+
+/**
+ * This file exports helpers for Legacy Extensions that want to embed a webextensions
+ * and exchange messages with the embedded WebExtension.
+ */
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "Extension",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+
+Cu.import("resource://gre/modules/ExtensionChild.jsm");
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+
+var {
+ BaseContext,
+} = ExtensionCommon;
+
+var {
+ Messenger,
+} = ExtensionChild;
+
+/**
+ * Instances created from this class provide to a legacy extension
+ * a simple API to exchange messages with a webextension.
+ */
+var LegacyExtensionContext = class extends BaseContext {
+ /**
+ * Create a new LegacyExtensionContext given a target Extension instance.
+ *
+ * @param {Extension} targetExtension
+ * The webextension instance associated with this context. This will be the
+ * instance of the newly created embedded webextension when this class is
+ * used through the EmbeddedWebExtensionsUtils.
+ */
+ constructor(targetExtension) {
+ super("legacy_extension", targetExtension);
+
+ // Legacy Extensions (xul overlays, bootstrap restartless and Addon SDK)
+ // runs with a systemPrincipal.
+ let addonPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
+ Object.defineProperty(
+ this, "principal",
+ {value: addonPrincipal, enumerable: true, configurable: true}
+ );
+
+ let cloneScope = Cu.Sandbox(this.principal, {});
+ Cu.setSandboxMetadata(cloneScope, {addonId: targetExtension.id});
+ Object.defineProperty(
+ this, "cloneScope",
+ {value: cloneScope, enumerable: true, configurable: true, writable: true}
+ );
+
+ let sender = {id: targetExtension.uuid};
+ let filter = {extensionId: targetExtension.id};
+ // Legacy addons live in the main process. Messages from other addons are
+ // Messages from WebExtensions are sent to the main process and forwarded via
+ // the parent process manager to the legacy extension.
+ this.messenger = new Messenger(this, [Services.cpmm], sender, filter);
+
+ this.api = {
+ browser: {
+ runtime: {
+ onConnect: this.messenger.onConnect("runtime.onConnect"),
+ onMessage: this.messenger.onMessage("runtime.onMessage"),
+ },
+ },
+ };
+ }
+
+ /**
+ * This method is called when the extension shuts down or is unloaded,
+ * and it nukes the cloneScope sandbox, if any.
+ */
+ unload() {
+ if (this.unloaded) {
+ throw new Error("Error trying to unload LegacyExtensionContext twice.");
+ }
+ super.unload();
+ Cu.nukeSandbox(this.cloneScope);
+ this.cloneScope = null;
+ }
+};
+
+var EmbeddedExtensionManager;
+
+/**
+ * Instances of this class are used internally by the exported EmbeddedWebExtensionsUtils
+ * to manage the embedded webextension instance and the related LegacyExtensionContext
+ * instance used to exchange messages with it.
+ */
+class EmbeddedExtension {
+ /**
+ * Create a new EmbeddedExtension given the add-on id and the base resource URI of the
+ * container add-on (the webextension resources will be loaded from the "webextension/"
+ * subdir of the base resource URI for the legacy extension add-on).
+ *
+ * @param {Object} containerAddonParams
+ * An object with the following properties:
+ * @param {string} containerAddonParams.id
+ * The Add-on id of the Legacy Extension which will contain the embedded webextension.
+ * @param {nsIURI} containerAddonParams.resourceURI
+ * The nsIURI of the Legacy Extension container add-on.
+ */
+ constructor({id, resourceURI}) {
+ this.addonId = id;
+ this.resourceURI = resourceURI;
+
+ // Setup status flag.
+ this.started = false;
+ }
+
+ /**
+ * Start the embedded webextension.
+ *
+ * @returns {Promise<LegacyContextAPI>} A promise which resolve to the API exposed to the
+ * legacy context.
+ */
+ startup() {
+ if (this.started) {
+ return Promise.reject(new Error("This embedded extension has already been started"));
+ }
+
+ // Setup the startup promise.
+ this.startupPromise = new Promise((resolve, reject) => {
+ let embeddedExtensionURI = Services.io.newURI("webextension/", null, this.resourceURI);
+
+ // This is the instance of the WebExtension embedded in the hybrid add-on.
+ this.extension = new Extension({
+ id: this.addonId,
+ resourceURI: embeddedExtensionURI,
+ });
+
+ // This callback is register to the "startup" event, emitted by the Extension instance
+ // after the extension manifest.json has been loaded without any errors, but before
+ // starting any of the defined contexts (which give the legacy part a chance to subscribe
+ // runtime.onMessage/onConnect listener before the background page has been loaded).
+ const onBeforeStarted = () => {
+ this.extension.off("startup", onBeforeStarted);
+
+ // Resolve the startup promise and reset the startupError.
+ this.started = true;
+ this.startupPromise = null;
+
+ // Create the legacy extension context, the legacy container addon
+ // needs to use it before the embedded webextension startup,
+ // because it is supposed to be used during the legacy container startup
+ // to subscribe its message listeners (which are supposed to be able to
+ // receive any message that the embedded part can try to send to it
+ // during its startup).
+ this.context = new LegacyExtensionContext(this.extension);
+
+ // Destroy the LegacyExtensionContext cloneScope when
+ // the embedded webextensions is unloaded.
+ this.extension.callOnClose({
+ close: () => {
+ this.context.unload();
+ },
+ });
+
+ // resolve startupPromise to execute any pending shutdown that has been
+ // chained to it.
+ resolve(this.context.api);
+ };
+
+ this.extension.on("startup", onBeforeStarted);
+
+ // Run ambedded extension startup and catch any error during embedded extension
+ // startup.
+ this.extension.startup().catch((err) => {
+ this.started = false;
+ this.startupPromise = null;
+ this.extension.off("startup", onBeforeStarted);
+
+ reject(err);
+ });
+ });
+
+ return this.startupPromise;
+ }
+
+ /**
+ * Shuts down the embedded webextension.
+ *
+ * @returns {Promise<void>} a promise that is resolved when the shutdown has been done
+ */
+ shutdown() {
+ EmbeddedExtensionManager.untrackEmbeddedExtension(this);
+
+ // If there is a pending startup, wait to be completed and then shutdown.
+ if (this.startupPromise) {
+ return this.startupPromise.then(() => {
+ this.extension.shutdown();
+ });
+ }
+
+ // Run shutdown now if the embedded webextension has been correctly started
+ if (this.extension && this.started && !this.extension.hasShutdown) {
+ this.extension.shutdown();
+ }
+
+ return Promise.resolve();
+ }
+}
+
+// Keep track on the created EmbeddedExtension instances and destroy
+// them when their container addon is going to be disabled or uninstalled.
+EmbeddedExtensionManager = {
+ // Map of the existent EmbeddedExtensions instances by addon id.
+ embeddedExtensionsByAddonId: new Map(),
+
+ untrackEmbeddedExtension(embeddedExtensionInstance) {
+ // Remove this instance from the tracked embedded extensions
+ let id = embeddedExtensionInstance.addonId;
+ if (this.embeddedExtensionsByAddonId.get(id) == embeddedExtensionInstance) {
+ this.embeddedExtensionsByAddonId.delete(id);
+ }
+ },
+
+ getEmbeddedExtensionFor({id, resourceURI}) {
+ let embeddedExtension = this.embeddedExtensionsByAddonId.get(id);
+
+ if (!embeddedExtension) {
+ embeddedExtension = new EmbeddedExtension({id, resourceURI});
+ // Keep track of the embedded extension instance.
+ this.embeddedExtensionsByAddonId.set(id, embeddedExtension);
+ }
+
+ return embeddedExtension;
+ },
+};
+
+this.LegacyExtensionsUtils = {
+ getEmbeddedExtensionFor: (addon) => {
+ return EmbeddedExtensionManager.getEmbeddedExtensionFor(addon);
+ },
+};
diff --git a/toolkit/components/webextensions/MessageChannel.jsm b/toolkit/components/webextensions/MessageChannel.jsm
new file mode 100644
index 000000000..c5b326405
--- /dev/null
+++ b/toolkit/components/webextensions/MessageChannel.jsm
@@ -0,0 +1,797 @@
+/* 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";
+
+/**
+ * This module provides wrappers around standard message managers to
+ * simplify bidirectional communication. It currently allows a caller to
+ * send a message to a single listener, and receive a reply. If there
+ * are no matching listeners, or the message manager disconnects before
+ * a reply is received, the caller is returned an error.
+ *
+ * The listener end may specify filters for the messages it wishes to
+ * receive, and the sender end likewise may specify recipient tags to
+ * match the filters.
+ *
+ * The message handler on the listener side may return its response
+ * value directly, or may return a promise, the resolution or rejection
+ * of which will be returned instead. The sender end likewise receives a
+ * promise which resolves or rejects to the listener's response.
+ *
+ *
+ * A basic setup works something like this:
+ *
+ * A content script adds a message listener to its global
+ * nsIContentFrameMessageManager, with an appropriate set of filters:
+ *
+ * {
+ * init(messageManager, window, extensionID) {
+ * this.window = window;
+ *
+ * MessageChannel.addListener(
+ * messageManager, "ContentScript:TouchContent",
+ * this);
+ *
+ * this.messageFilterStrict = {
+ * innerWindowID: getInnerWindowID(window),
+ * extensionID: extensionID,
+ * };
+ *
+ * this.messageFilterPermissive = {
+ * outerWindowID: getOuterWindowID(window),
+ * };
+ * },
+ *
+ * receiveMessage({ target, messageName, sender, recipient, data }) {
+ * if (messageName == "ContentScript:TouchContent") {
+ * return new Promise(resolve => {
+ * this.touchWindow(data.touchWith, result => {
+ * resolve({ touchResult: result });
+ * });
+ * });
+ * }
+ * },
+ * };
+ *
+ * A script in the parent process sends a message to the content process
+ * via a tab message manager, including recipient tags to match its
+ * filter, and an optional sender tag to identify itself:
+ *
+ * let data = { touchWith: "pencil" };
+ * let sender = { extensionID, contextID };
+ * let recipient = { innerWindowID: tab.linkedBrowser.innerWindowID, extensionID };
+ *
+ * MessageChannel.sendMessage(
+ * tab.linkedBrowser.messageManager, "ContentScript:TouchContent",
+ * data, {recipient, sender}
+ * ).then(result => {
+ * alert(result.touchResult);
+ * });
+ *
+ * Since the lifetimes of message senders and receivers may not always
+ * match, either side of the message channel may cancel pending
+ * responses which match its sender or recipient tags.
+ *
+ * For the above client, this might be done from an
+ * inner-window-destroyed observer, when its target scope is destroyed:
+ *
+ * observe(subject, topic, data) {
+ * if (topic == "inner-window-destroyed") {
+ * let innerWindowID = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
+ *
+ * MessageChannel.abortResponses({ innerWindowID });
+ * }
+ * },
+ *
+ * From the parent, it may be done when its context is being destroyed:
+ *
+ * onDestroy() {
+ * MessageChannel.abortResponses({
+ * extensionID: this.extensionID,
+ * contextID: this.contextID,
+ * });
+ * },
+ *
+ */
+
+this.EXPORTED_SYMBOLS = ["MessageChannel"];
+
+/* globals MessageChannel */
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils",
+ "resource://gre/modules/ExtensionUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
+ "resource://gre/modules/PromiseUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "MessageManagerProxy",
+ () => ExtensionUtils.MessageManagerProxy);
+
+/**
+ * Handles the mapping and dispatching of messages to their registered
+ * handlers. There is one broker per message manager and class of
+ * messages. Each class of messages is mapped to one native message
+ * name, e.g., "MessageChannel:Message", and is dispatched to handlers
+ * based on an internal message name, e.g., "Extension:ExecuteScript".
+ */
+class FilteringMessageManager {
+ /**
+ * @param {string} messageName
+ * The name of the native message this broker listens for.
+ * @param {function} callback
+ * A function which is called for each message after it has been
+ * mapped to its handler. The function receives two arguments:
+ *
+ * result:
+ * An object containing either a `handler` or an `error` property.
+ * If no error occurs, `handler` will be a matching handler that
+ * was registered by `addHandler`. Otherwise, the `error` property
+ * will contain an object describing the error.
+ *
+ * data:
+ * An object describing the message, as defined in
+ * `MessageChannel.addListener`.
+ * @param {nsIMessageListenerManager} messageManager
+ */
+ constructor(messageName, callback, messageManager) {
+ this.messageName = messageName;
+ this.callback = callback;
+ this.messageManager = messageManager;
+
+ this.messageManager.addMessageListener(this.messageName, this, true);
+
+ this.handlers = new Map();
+ }
+
+ /**
+ * Receives a message from our message manager, maps it to a handler, and
+ * passes the result to our message callback.
+ */
+ receiveMessage({data, target}) {
+ let handlers = Array.from(this.getHandlers(data.messageName, data.sender, data.recipient));
+
+ data.target = target;
+ this.callback(handlers, data);
+ }
+
+ /**
+ * Iterates over all handlers for the given message name. If `recipient`
+ * is provided, only iterates over handlers whose filters match it.
+ *
+ * @param {string|number} messageName
+ * The message for which to return handlers.
+ * @param {object} sender
+ * The sender data on which to filter handlers.
+ * @param {object} recipient
+ * The recipient data on which to filter handlers.
+ */
+ * getHandlers(messageName, sender, recipient) {
+ let handlers = this.handlers.get(messageName) || new Set();
+ for (let handler of handlers) {
+ if (MessageChannel.matchesFilter(handler.messageFilterStrict || {}, recipient) &&
+ MessageChannel.matchesFilter(handler.messageFilterPermissive || {}, recipient, false) &&
+ (!handler.filterMessage || handler.filterMessage(sender, recipient))) {
+ yield handler;
+ }
+ }
+ }
+
+ /**
+ * Registers a handler for the given message.
+ *
+ * @param {string} messageName
+ * The internal message name for which to register the handler.
+ * @param {object} handler
+ * An opaque handler object. The object may have a
+ * `messageFilterStrict` and/or a `messageFilterPermissive`
+ * property and/or a `filterMessage` method on which to filter messages.
+ *
+ * Final dispatching is handled by the message callback passed to
+ * the constructor.
+ */
+ addHandler(messageName, handler) {
+ if (!this.handlers.has(messageName)) {
+ this.handlers.set(messageName, new Set());
+ }
+
+ this.handlers.get(messageName).add(handler);
+ }
+
+ /**
+ * Unregisters a handler for the given message.
+ *
+ * @param {string} messageName
+ * The internal message name for which to unregister the handler.
+ * @param {object} handler
+ * The handler object to unregister.
+ */
+ removeHandler(messageName, handler) {
+ this.handlers.get(messageName).delete(handler);
+ }
+}
+
+/**
+ * Manages mappings of message managers to their corresponding message
+ * brokers. Brokers are lazily created for each message manager the
+ * first time they are accessed. In the case of content frame message
+ * managers, they are also automatically destroyed when the frame
+ * unload event fires.
+ */
+class FilteringMessageManagerMap extends Map {
+ // Unfortunately, we can't use a WeakMap for this, because message
+ // managers do not support preserved wrappers.
+
+ /**
+ * @param {string} messageName
+ * The native message name passed to `FilteringMessageManager` constructors.
+ * @param {function} callback
+ * The message callback function passed to
+ * `FilteringMessageManager` constructors.
+ */
+ constructor(messageName, callback) {
+ super();
+
+ this.messageName = messageName;
+ this.callback = callback;
+ }
+
+ /**
+ * Returns, and possibly creates, a message broker for the given
+ * message manager.
+ *
+ * @param {nsIMessageListenerManager} target
+ * The message manager for which to return a broker.
+ *
+ * @returns {FilteringMessageManager}
+ */
+ get(target) {
+ if (this.has(target)) {
+ return super.get(target);
+ }
+
+ let broker = new FilteringMessageManager(this.messageName, this.callback, target);
+ this.set(target, broker);
+
+ if (target instanceof Ci.nsIDOMEventTarget) {
+ let onUnload = event => {
+ target.removeEventListener("unload", onUnload);
+ this.delete(target);
+ };
+ target.addEventListener("unload", onUnload);
+ }
+
+ return broker;
+ }
+}
+
+const MESSAGE_MESSAGE = "MessageChannel:Message";
+const MESSAGE_RESPONSE = "MessageChannel:Response";
+
+this.MessageChannel = {
+ init() {
+ Services.obs.addObserver(this, "message-manager-close", false);
+ Services.obs.addObserver(this, "message-manager-disconnect", false);
+
+ this.messageManagers = new FilteringMessageManagerMap(
+ MESSAGE_MESSAGE, this._handleMessage.bind(this));
+
+ this.responseManagers = new FilteringMessageManagerMap(
+ MESSAGE_RESPONSE, this._handleResponse.bind(this));
+
+ /**
+ * Contains a list of pending responses, either waiting to be
+ * received or waiting to be sent. @see _addPendingResponse
+ */
+ this.pendingResponses = new Set();
+ },
+
+ RESULT_SUCCESS: 0,
+ RESULT_DISCONNECTED: 1,
+ RESULT_NO_HANDLER: 2,
+ RESULT_MULTIPLE_HANDLERS: 3,
+ RESULT_ERROR: 4,
+ RESULT_NO_RESPONSE: 5,
+
+ REASON_DISCONNECTED: {
+ result: this.RESULT_DISCONNECTED,
+ message: "Message manager disconnected",
+ },
+
+ /**
+ * Specifies that only a single listener matching the specified
+ * recipient tag may be listening for the given message, at the other
+ * end of the target message manager.
+ *
+ * If no matching listeners exist, a RESULT_NO_HANDLER error will be
+ * returned. If multiple matching listeners exist, a
+ * RESULT_MULTIPLE_HANDLERS error will be returned.
+ */
+ RESPONSE_SINGLE: 0,
+
+ /**
+ * If multiple message managers matching the specified recipient tag
+ * are listening for a message, all listeners are notified, but only
+ * the first response or error is returned.
+ *
+ * Only handlers which return a value other than `undefined` are
+ * considered to have responded. Returning a Promise which evaluates
+ * to `undefined` is interpreted as an explicit response.
+ *
+ * If no matching listeners exist, a RESULT_NO_HANDLER error will be
+ * returned. If no listeners return a response, a RESULT_NO_RESPONSE
+ * error will be returned.
+ */
+ RESPONSE_FIRST: 1,
+
+ /**
+ * If multiple message managers matching the specified recipient tag
+ * are listening for a message, all listeners are notified, and all
+ * responses are returned as an array, once all listeners have
+ * replied.
+ */
+ RESPONSE_ALL: 2,
+
+ /**
+ * Fire-and-forget: The sender of this message does not expect a reply.
+ */
+ RESPONSE_NONE: 3,
+
+ /**
+ * Initializes message handlers for the given message managers if needed.
+ *
+ * @param {Array<nsIMessageListenerManager>} messageManagers
+ */
+ setupMessageManagers(messageManagers) {
+ for (let mm of messageManagers) {
+ // This call initializes a FilteringMessageManager for |mm| if needed.
+ // The FilteringMessageManager must be created to make sure that senders
+ // of messages that expect a reply, such as MessageChannel:Message, do
+ // actually receive a default reply even if there are no explicit message
+ // handlers.
+ this.messageManagers.get(mm);
+ }
+ },
+
+ /**
+ * Returns true if the properties of the `data` object match those in
+ * the `filter` object. Matching is done on a strict equality basis,
+ * and the behavior varies depending on the value of the `strict`
+ * parameter.
+ *
+ * @param {object} filter
+ * The filter object to match against.
+ * @param {object} data
+ * The data object being matched.
+ * @param {boolean} [strict=false]
+ * If true, all properties in the `filter` object have a
+ * corresponding property in `data` with the same value. If
+ * false, properties present in both objects must have the same
+ * value.
+ * @returns {boolean} True if the objects match.
+ */
+ matchesFilter(filter, data, strict = true) {
+ if (strict) {
+ return Object.keys(filter).every(key => {
+ return key in data && data[key] === filter[key];
+ });
+ }
+ return Object.keys(filter).every(key => {
+ return !(key in data) || data[key] === filter[key];
+ });
+ },
+
+ /**
+ * Adds a message listener to the given message manager.
+ *
+ * @param {nsIMessageListenerManager|Array<nsIMessageListenerManager>} targets
+ * The message managers on which to listen.
+ * @param {string|number} messageName
+ * The name of the message to listen for.
+ * @param {MessageReceiver} handler
+ * The handler to dispatch to. Must be an object with the following
+ * properties:
+ *
+ * receiveMessage:
+ * A method which is called for each message received by the
+ * listener. The method takes one argument, an object, with the
+ * following properties:
+ *
+ * messageName:
+ * The internal message name, as passed to `sendMessage`.
+ *
+ * target:
+ * The message manager which received this message.
+ *
+ * channelId:
+ * The internal ID of the transaction, used to map responses to
+ * the original sender.
+ *
+ * sender:
+ * An object describing the sender, as passed to `sendMessage`.
+ *
+ * recipient:
+ * An object describing the recipient, as passed to
+ * `sendMessage`.
+ *
+ * data:
+ * The contents of the message, as passed to `sendMessage`.
+ *
+ * The method may return any structured-clone-compatible
+ * object, which will be returned as a response to the message
+ * sender. It may also instead return a `Promise`, the
+ * resolution or rejection value of which will likewise be
+ * returned to the message sender.
+ *
+ * messageFilterStrict:
+ * An object containing arbitrary properties on which to filter
+ * received messages. Messages will only be dispatched to this
+ * object if the `recipient` object passed to `sendMessage`
+ * matches this filter, as determined by `matchesFilter` with
+ * `strict=true`.
+ *
+ * messageFilterPermissive:
+ * An object containing arbitrary properties on which to filter
+ * received messages. Messages will only be dispatched to this
+ * object if the `recipient` object passed to `sendMessage`
+ * matches this filter, as determined by `matchesFilter` with
+ * `strict=false`.
+ *
+ * filterMessage:
+ * An optional function that prevents the handler from handling a
+ * message by returning `false`. See `getHandlers` for the parameters.
+ */
+ addListener(targets, messageName, handler) {
+ for (let target of [].concat(targets)) {
+ this.messageManagers.get(target).addHandler(messageName, handler);
+ }
+ },
+
+ /**
+ * Removes a message listener from the given message manager.
+ *
+ * @param {nsIMessageListenerManager|Array<nsIMessageListenerManager>} targets
+ * The message managers on which to stop listening.
+ * @param {string|number} messageName
+ * The name of the message to stop listening for.
+ * @param {MessageReceiver} handler
+ * The handler to stop dispatching to.
+ */
+ removeListener(targets, messageName, handler) {
+ for (let target of [].concat(targets)) {
+ if (this.messageManagers.has(target)) {
+ this.messageManagers.get(target).removeHandler(messageName, handler);
+ }
+ }
+ },
+
+ /**
+ * Sends a message via the given message manager. Returns a promise which
+ * resolves or rejects with the return value of the message receiver.
+ *
+ * The promise also rejects if there is no matching listener, or the other
+ * side of the message manager disconnects before the response is received.
+ *
+ * @param {nsIMessageSender} target
+ * The message manager on which to send the message.
+ * @param {string} messageName
+ * The name of the message to send, as passed to `addListener`.
+ * @param {object} data
+ * A structured-clone-compatible object to send to the message
+ * recipient.
+ * @param {object} [options]
+ * An object containing any of the following properties:
+ * @param {object} [options.recipient]
+ * A structured-clone-compatible object to identify the message
+ * recipient. The object must match the `messageFilterStrict` and
+ * `messageFilterPermissive` filters defined by recipients in order
+ * for the message to be received.
+ * @param {object} [options.sender]
+ * A structured-clone-compatible object to identify the message
+ * sender. This object may also be used to avoid delivering the
+ * message to the sender, and as a filter to prematurely
+ * abort responses when the sender is being destroyed.
+ * @see `abortResponses`.
+ * @param {integer} [options.responseType=RESPONSE_SINGLE]
+ * Specifies the type of response expected. See the `RESPONSE_*`
+ * contents for details.
+ * @returns {Promise}
+ */
+ sendMessage(target, messageName, data, options = {}) {
+ let sender = options.sender || {};
+ let recipient = options.recipient || {};
+ let responseType = options.responseType || this.RESPONSE_SINGLE;
+
+ let channelId = ExtensionUtils.getUniqueId();
+ let message = {messageName, channelId, sender, recipient, data, responseType};
+
+ if (responseType == this.RESPONSE_NONE) {
+ try {
+ target.sendAsyncMessage(MESSAGE_MESSAGE, message);
+ } catch (e) {
+ // Caller is not expecting a reply, so dump the error to the console.
+ Cu.reportError(e);
+ return Promise.reject(e);
+ }
+ return Promise.resolve(); // Not expecting any reply.
+ }
+
+ let deferred = PromiseUtils.defer();
+ deferred.sender = recipient;
+ deferred.messageManager = target;
+
+ this._addPendingResponse(deferred);
+
+ // The channel ID is used as the message name when routing responses.
+ // Add a message listener to the response broker, and remove it once
+ // we've gotten (or canceled) a response.
+ let broker = this.responseManagers.get(target);
+ broker.addHandler(channelId, deferred);
+
+ let cleanup = () => {
+ broker.removeHandler(channelId, deferred);
+ };
+ deferred.promise.then(cleanup, cleanup);
+
+ try {
+ target.sendAsyncMessage(MESSAGE_MESSAGE, message);
+ } catch (e) {
+ deferred.reject(e);
+ }
+ return deferred.promise;
+ },
+
+ _callHandlers(handlers, data) {
+ let responseType = data.responseType;
+
+ // At least one handler is required for all response types but
+ // RESPONSE_ALL.
+ if (handlers.length == 0 && responseType != this.RESPONSE_ALL) {
+ return Promise.reject({result: MessageChannel.RESULT_NO_HANDLER,
+ message: "No matching message handler"});
+ }
+
+ if (responseType == this.RESPONSE_SINGLE) {
+ if (handlers.length > 1) {
+ return Promise.reject({result: MessageChannel.RESULT_MULTIPLE_HANDLERS,
+ message: `Multiple matching handlers for ${data.messageName}`});
+ }
+
+ // Note: We use `new Promise` rather than `Promise.resolve` here
+ // so that errors from the handler are trapped and converted into
+ // rejected promises.
+ return new Promise(resolve => {
+ resolve(handlers[0].receiveMessage(data));
+ });
+ }
+
+ let responses = handlers.map(handler => {
+ try {
+ return handler.receiveMessage(data);
+ } catch (e) {
+ return Promise.reject(e);
+ }
+ });
+ responses = responses.filter(response => response !== undefined);
+
+ switch (responseType) {
+ case this.RESPONSE_FIRST:
+ if (responses.length == 0) {
+ return Promise.reject({result: MessageChannel.RESULT_NO_RESPONSE,
+ message: "No handler returned a response"});
+ }
+
+ return Promise.race(responses);
+
+ case this.RESPONSE_ALL:
+ return Promise.all(responses);
+ }
+ return Promise.reject({message: "Invalid response type"});
+ },
+
+ /**
+ * Handles dispatching message callbacks from the message brokers to their
+ * appropriate `MessageReceivers`, and routing the responses back to the
+ * original senders.
+ *
+ * Each handler object is a `MessageReceiver` object as passed to
+ * `addListener`.
+ *
+ * @param {Array<MessageHandler>} handlers
+ * @param {object} data
+ * @param {nsIMessageSender|{messageManager:nsIMessageSender}} data.target
+ */
+ _handleMessage(handlers, data) {
+ if (data.responseType == this.RESPONSE_NONE) {
+ handlers.forEach(handler => {
+ // The sender expects no reply, so dump any errors to the console.
+ new Promise(resolve => {
+ resolve(handler.receiveMessage(data));
+ }).catch(e => {
+ Cu.reportError(e.stack ? `${e}\n${e.stack}` : e.message || e);
+ });
+ });
+ // Note: Unhandled messages are silently dropped.
+ return;
+ }
+
+ let target = new MessageManagerProxy(data.target);
+
+ let deferred = {
+ sender: data.sender,
+ messageManager: target,
+ };
+ deferred.promise = new Promise((resolve, reject) => {
+ deferred.reject = reject;
+
+ this._callHandlers(handlers, data).then(resolve, reject);
+ }).then(
+ value => {
+ let response = {
+ result: this.RESULT_SUCCESS,
+ messageName: data.channelId,
+ recipient: {},
+ value,
+ };
+
+ target.sendAsyncMessage(MESSAGE_RESPONSE, response);
+ },
+ error => {
+ let response = {
+ result: this.RESULT_ERROR,
+ messageName: data.channelId,
+ recipient: {},
+ error: {},
+ };
+
+ if (error && typeof(error) == "object") {
+ if (error.result) {
+ response.result = error.result;
+ }
+ // Error objects are not structured-clonable, so just copy
+ // over the important properties.
+ for (let key of ["fileName", "filename", "lineNumber",
+ "columnNumber", "message", "stack", "result"]) {
+ if (key in error) {
+ response.error[key] = error[key];
+ }
+ }
+ }
+
+ target.sendAsyncMessage(MESSAGE_RESPONSE, response);
+ }).catch(e => {
+ Cu.reportError(e);
+ }).then(() => {
+ target.dispose();
+ });
+
+ this._addPendingResponse(deferred);
+ },
+
+ /**
+ * Handles message callbacks from the response brokers.
+ *
+ * Each handler object is a deferred object created by `sendMessage`, and
+ * should be resolved or rejected based on the contents of the response.
+ *
+ * @param {Array<MessageHandler>} handlers
+ * @param {object} data
+ * @param {nsIMessageSender|{messageManager:nsIMessageSender}} data.target
+ */
+ _handleResponse(handlers, data) {
+ // If we have an error at this point, we have handler to report it to,
+ // so just log it.
+ if (handlers.length == 0) {
+ Cu.reportError(`No matching message response handler for ${data.messageName}`);
+ } else if (handlers.length > 1) {
+ Cu.reportError(`Multiple matching response handlers for ${data.messageName}`);
+ } else if (data.result === this.RESULT_SUCCESS) {
+ handlers[0].resolve(data.value);
+ } else {
+ handlers[0].reject(data.error);
+ }
+ },
+
+ /**
+ * Adds a pending response to the the `pendingResponses` list.
+ *
+ * The response object must be a deferred promise with the following
+ * properties:
+ *
+ * promise:
+ * The promise object which resolves or rejects when the response
+ * is no longer pending.
+ *
+ * reject:
+ * A function which, when called, causes the `promise` object to be
+ * rejected.
+ *
+ * sender:
+ * A sender object, as passed to `sendMessage.
+ *
+ * messageManager:
+ * The message manager the response will be sent or received on.
+ *
+ * When the promise resolves or rejects, it will be removed from the
+ * list.
+ *
+ * These values are used to clear pending responses when execution
+ * contexts are destroyed.
+ *
+ * @param {Deferred} deferred
+ */
+ _addPendingResponse(deferred) {
+ let cleanup = () => {
+ this.pendingResponses.delete(deferred);
+ };
+ this.pendingResponses.add(deferred);
+ deferred.promise.then(cleanup, cleanup);
+ },
+
+ /**
+ * Aborts any pending message responses to senders matching the given
+ * filter.
+ *
+ * @param {object} sender
+ * The object on which to filter senders, as determined by
+ * `matchesFilter`.
+ * @param {object} [reason]
+ * An optional object describing the reason the response was aborted.
+ * Will be passed to the promise rejection handler of all aborted
+ * responses.
+ */
+ abortResponses(sender, reason = this.REASON_DISCONNECTED) {
+ for (let response of this.pendingResponses) {
+ if (this.matchesFilter(sender, response.sender)) {
+ response.reject(reason);
+ }
+ }
+ },
+
+ /**
+ * Aborts any pending message responses to the broker for the given
+ * message manager.
+ *
+ * @param {nsIMessageListenerManager} target
+ * The message manager for which to abort brokers.
+ * @param {object} reason
+ * An object describing the reason the responses were aborted.
+ * Will be passed to the promise rejection handler of all aborted
+ * responses.
+ */
+ abortMessageManager(target, reason) {
+ for (let response of this.pendingResponses) {
+ if (MessageManagerProxy.matches(response.messageManager, target)) {
+ response.reject(reason);
+ }
+ }
+ },
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "message-manager-close":
+ case "message-manager-disconnect":
+ try {
+ if (this.responseManagers.has(subject)) {
+ this.abortMessageManager(subject, this.REASON_DISCONNECTED);
+ }
+ } finally {
+ this.responseManagers.delete(subject);
+ this.messageManagers.delete(subject);
+ }
+ break;
+ }
+ },
+};
+
+MessageChannel.init();
diff --git a/toolkit/components/webextensions/NativeMessaging.jsm b/toolkit/components/webextensions/NativeMessaging.jsm
new file mode 100644
index 000000000..3d8658a3f
--- /dev/null
+++ b/toolkit/components/webextensions/NativeMessaging.jsm
@@ -0,0 +1,443 @@
+/* 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";
+
+this.EXPORTED_SYMBOLS = ["HostManifestManager", "NativeApp"];
+/* globals NativeApp */
+
+const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
+
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
+ "resource://gre/modules/AsyncShutdown.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionChild",
+ "resource://gre/modules/ExtensionChild.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Subprocess",
+ "resource://gre/modules/Subprocess.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout",
+ "resource://gre/modules/Timer.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
+ "resource://gre/modules/Timer.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry",
+ "resource://gre/modules/WindowsRegistry.jsm");
+
+const HOST_MANIFEST_SCHEMA = "chrome://extensions/content/schemas/native_host_manifest.json";
+const VALID_APPLICATION = /^\w+(\.\w+)*$/;
+
+// For a graceful shutdown (i.e., when the extension is unloaded or when it
+// explicitly calls disconnect() on a native port), how long we give the native
+// application to exit before we start trying to kill it. (in milliseconds)
+const GRACEFUL_SHUTDOWN_TIME = 3000;
+
+// Hard limits on maximum message size that can be read/written
+// These are defined in the native messaging documentation, note that
+// the write limit is imposed by the "wire protocol" in which message
+// boundaries are defined by preceding each message with its length as
+// 4-byte unsigned integer so this is the largest value that can be
+// represented. Good luck generating a serialized message that large,
+// the practical write limit is likely to be dictated by available memory.
+const MAX_READ = 1024 * 1024;
+const MAX_WRITE = 0xffffffff;
+
+// Preferences that can lower the message size limits above,
+// used for testing the limits.
+const PREF_MAX_READ = "webextensions.native-messaging.max-input-message-bytes";
+const PREF_MAX_WRITE = "webextensions.native-messaging.max-output-message-bytes";
+
+const REGPATH = "Software\\Mozilla\\NativeMessagingHosts";
+
+this.HostManifestManager = {
+ _initializePromise: null,
+ _lookup: null,
+
+ init() {
+ if (!this._initializePromise) {
+ let platform = AppConstants.platform;
+ if (platform == "win") {
+ this._lookup = this._winLookup;
+ } else if (platform == "macosx" || platform == "linux") {
+ let dirs = [
+ Services.dirsvc.get("XREUserNativeMessaging", Ci.nsIFile).path,
+ Services.dirsvc.get("XRESysNativeMessaging", Ci.nsIFile).path,
+ ];
+ this._lookup = (application, context) => this._tryPaths(application, dirs, context);
+ } else {
+ throw new Error(`Native messaging is not supported on ${AppConstants.platform}`);
+ }
+ this._initializePromise = Schemas.load(HOST_MANIFEST_SCHEMA);
+ }
+ return this._initializePromise;
+ },
+
+ _winLookup(application, context) {
+ const REGISTRY = Ci.nsIWindowsRegKey;
+ let regPath = `${REGPATH}\\${application}`;
+ let path = WindowsRegistry.readRegKey(REGISTRY.ROOT_KEY_CURRENT_USER,
+ regPath, "", REGISTRY.WOW64_64);
+ if (!path) {
+ path = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
+ regPath, "", REGISTRY.WOW64_64);
+ }
+ if (!path) {
+ return null;
+ }
+ return this._tryPath(path, application, context)
+ .then(manifest => manifest ? {path, manifest} : null);
+ },
+
+ _tryPath(path, application, context) {
+ return Promise.resolve()
+ .then(() => OS.File.read(path, {encoding: "utf-8"}))
+ .then(data => {
+ let manifest;
+ try {
+ manifest = JSON.parse(data);
+ } catch (ex) {
+ let msg = `Error parsing native host manifest ${path}: ${ex.message}`;
+ Cu.reportError(msg);
+ return null;
+ }
+
+ let normalized = Schemas.normalize(manifest, "manifest.NativeHostManifest", context);
+ if (normalized.error) {
+ Cu.reportError(normalized.error);
+ return null;
+ }
+ manifest = normalized.value;
+ if (manifest.name != application) {
+ let msg = `Native host manifest ${path} has name property ${manifest.name} (expected ${application})`;
+ Cu.reportError(msg);
+ return null;
+ }
+ return normalized.value;
+ }).catch(ex => {
+ if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) {
+ return null;
+ }
+ throw ex;
+ });
+ },
+
+ _tryPaths: Task.async(function* (application, dirs, context) {
+ for (let dir of dirs) {
+ let path = OS.Path.join(dir, `${application}.json`);
+ let manifest = yield this._tryPath(path, application, context);
+ if (manifest) {
+ return {path, manifest};
+ }
+ }
+ return null;
+ }),
+
+ /**
+ * Search for a valid native host manifest for the given application name.
+ * The directories searched and rules for manifest validation are all
+ * detailed in the native messaging documentation.
+ *
+ * @param {string} application The name of the applciation to search for.
+ * @param {object} context A context object as expected by Schemas.normalize.
+ * @returns {object} The contents of the validated manifest, or null if
+ * no valid manifest can be found for this application.
+ */
+ lookupApplication(application, context) {
+ if (!VALID_APPLICATION.test(application)) {
+ throw new Error(`Invalid application "${application}"`);
+ }
+ return this.init().then(() => this._lookup(application, context));
+ },
+};
+
+this.NativeApp = class extends EventEmitter {
+ /**
+ * @param {BaseContext} context The context that initiated the native app.
+ * @param {string} application The identifier of the native app.
+ */
+ constructor(context, application) {
+ super();
+
+ this.context = context;
+ this.name = application;
+
+ // We want a close() notification when the window is destroyed.
+ this.context.callOnClose(this);
+
+ this.proc = null;
+ this.readPromise = null;
+ this.sendQueue = [];
+ this.writePromise = null;
+ this.sentDisconnect = false;
+
+ this.startupPromise = HostManifestManager.lookupApplication(application, context)
+ .then(hostInfo => {
+ // Put the two errors together to not leak information about whether a native
+ // application is installed to addons that do not have the right permission.
+ if (!hostInfo || !hostInfo.manifest.allowed_extensions.includes(context.extension.id)) {
+ throw new context.cloneScope.Error(`This extension does not have permission to use native application ${application} (or the application is not installed)`);
+ }
+
+ let command = hostInfo.manifest.path;
+ if (AppConstants.platform == "win") {
+ // OS.Path.join() ignores anything before the last absolute path
+ // it sees, so if command is already absolute, it remains unchanged
+ // here. If it is relative, we get the proper absolute path here.
+ command = OS.Path.join(OS.Path.dirname(hostInfo.path), command);
+ }
+
+ let subprocessOpts = {
+ command: command,
+ arguments: [hostInfo.path],
+ workdir: OS.Path.dirname(command),
+ stderr: "pipe",
+ };
+ return Subprocess.call(subprocessOpts);
+ }).then(proc => {
+ this.startupPromise = null;
+ this.proc = proc;
+ this._startRead();
+ this._startWrite();
+ this._startStderrRead();
+ }).catch(err => {
+ this.startupPromise = null;
+ Cu.reportError(err instanceof Error ? err : err.message);
+ this._cleanup(err);
+ });
+ }
+
+ /**
+ * Open a connection to a native messaging host.
+ *
+ * @param {BaseContext} context The context associated with the port.
+ * @param {nsIMessageSender} messageManager The message manager used to send
+ * and receive messages from the port's creator.
+ * @param {string} portId A unique internal ID that identifies the port.
+ * @param {object} sender The object describing the creator of the connection
+ * request.
+ * @param {string} application The name of the native messaging host.
+ */
+ static onConnectNative(context, messageManager, portId, sender, application) {
+ let app = new NativeApp(context, application);
+ let port = new ExtensionChild.Port(context, messageManager, [Services.mm], "", portId, sender, sender);
+ app.once("disconnect", (what, err) => port.disconnect(err));
+
+ /* eslint-disable mozilla/balanced-listeners */
+ app.on("message", (what, msg) => port.postMessage(msg));
+ /* eslint-enable mozilla/balanced-listeners */
+
+ port.registerOnMessage(msg => app.send(msg));
+ port.registerOnDisconnect(msg => app.close());
+ }
+
+ /**
+ * @param {BaseContext} context The scope from where `message` originates.
+ * @param {*} message A message from the extension, meant for a native app.
+ * @returns {ArrayBuffer} An ArrayBuffer that can be sent to the native app.
+ */
+ static encodeMessage(context, message) {
+ message = context.jsonStringify(message);
+ let buffer = new TextEncoder().encode(message).buffer;
+ if (buffer.byteLength > NativeApp.maxWrite) {
+ throw new context.cloneScope.Error("Write too big");
+ }
+ return buffer;
+ }
+
+ // A port is definitely "alive" if this.proc is non-null. But we have
+ // to provide a live port object immediately when connecting so we also
+ // need to consider a port alive if proc is null but the startupPromise
+ // is still pending.
+ get _isDisconnected() {
+ return (!this.proc && !this.startupPromise);
+ }
+
+ _startRead() {
+ if (this.readPromise) {
+ throw new Error("Entered _startRead() while readPromise is non-null");
+ }
+ this.readPromise = this.proc.stdout.readUint32()
+ .then(len => {
+ if (len > NativeApp.maxRead) {
+ throw new this.context.cloneScope.Error(`Native application tried to send a message of ${len} bytes, which exceeds the limit of ${NativeApp.maxRead} bytes.`);
+ }
+ return this.proc.stdout.readJSON(len);
+ }).then(msg => {
+ this.emit("message", msg);
+ this.readPromise = null;
+ this._startRead();
+ }).catch(err => {
+ if (err.errorCode != Subprocess.ERROR_END_OF_FILE) {
+ Cu.reportError(err instanceof Error ? err : err.message);
+ }
+ this._cleanup(err);
+ });
+ }
+
+ _startWrite() {
+ if (this.sendQueue.length == 0) {
+ return;
+ }
+
+ if (this.writePromise) {
+ throw new Error("Entered _startWrite() while writePromise is non-null");
+ }
+
+ let buffer = this.sendQueue.shift();
+ let uintArray = Uint32Array.of(buffer.byteLength);
+
+ this.writePromise = Promise.all([
+ this.proc.stdin.write(uintArray.buffer),
+ this.proc.stdin.write(buffer),
+ ]).then(() => {
+ this.writePromise = null;
+ this._startWrite();
+ }).catch(err => {
+ Cu.reportError(err.message);
+ this._cleanup(err);
+ });
+ }
+
+ _startStderrRead() {
+ let proc = this.proc;
+ let app = this.name;
+ Task.spawn(function* () {
+ let partial = "";
+ while (true) {
+ let data = yield proc.stderr.readString();
+ if (data.length == 0) {
+ // We have hit EOF, just stop reading
+ if (partial) {
+ Services.console.logStringMessage(`stderr output from native app ${app}: ${partial}`);
+ }
+ break;
+ }
+
+ let lines = data.split(/\r?\n/);
+ lines[0] = partial + lines[0];
+ partial = lines.pop();
+
+ for (let line of lines) {
+ Services.console.logStringMessage(`stderr output from native app ${app}: ${line}`);
+ }
+ }
+ });
+ }
+
+ send(msg) {
+ if (this._isDisconnected) {
+ throw new this.context.cloneScope.Error("Attempt to postMessage on disconnected port");
+ }
+ if (Cu.getClassName(msg, true) != "ArrayBuffer") {
+ // This error cannot be triggered by extensions; it indicates an error in
+ // our implementation.
+ throw new Error("The message to the native messaging host is not an ArrayBuffer");
+ }
+
+ let buffer = msg;
+
+ if (buffer.byteLength > NativeApp.maxWrite) {
+ throw new this.context.cloneScope.Error("Write too big");
+ }
+
+ this.sendQueue.push(buffer);
+ if (!this.startupPromise && !this.writePromise) {
+ this._startWrite();
+ }
+ }
+
+ // Shut down the native application and also signal to the extension
+ // that the connect has been disconnected.
+ _cleanup(err) {
+ this.context.forgetOnClose(this);
+
+ let doCleanup = () => {
+ // Set a timer to kill the process gracefully after one timeout
+ // interval and kill it forcefully after two intervals.
+ let timer = setTimeout(() => {
+ this.proc.kill(GRACEFUL_SHUTDOWN_TIME);
+ }, GRACEFUL_SHUTDOWN_TIME);
+
+ let promise = Promise.all([
+ this.proc.stdin.close()
+ .catch(err => {
+ if (err.errorCode != Subprocess.ERROR_END_OF_FILE) {
+ throw err;
+ }
+ }),
+ this.proc.wait(),
+ ]).then(() => {
+ this.proc = null;
+ clearTimeout(timer);
+ });
+
+ AsyncShutdown.profileBeforeChange.addBlocker(
+ `Native Messaging: Wait for application ${this.name} to exit`,
+ promise);
+
+ promise.then(() => {
+ AsyncShutdown.profileBeforeChange.removeBlocker(promise);
+ });
+
+ return promise;
+ };
+
+ if (this.proc) {
+ doCleanup();
+ } else if (this.startupPromise) {
+ this.startupPromise.then(doCleanup);
+ }
+
+ if (!this.sentDisconnect) {
+ this.sentDisconnect = true;
+ if (err && err.errorCode == Subprocess.ERROR_END_OF_FILE) {
+ err = null;
+ }
+ this.emit("disconnect", err);
+ }
+ }
+
+ // Called from Context when the extension is shut down.
+ close() {
+ this._cleanup();
+ }
+
+ sendMessage(msg) {
+ let responsePromise = new Promise((resolve, reject) => {
+ this.once("message", (what, msg) => { resolve(msg); });
+ this.once("disconnect", (what, err) => { reject(err); });
+ });
+
+ let result = this.startupPromise.then(() => {
+ this.send(msg);
+ return responsePromise;
+ });
+
+ result.then(() => {
+ this._cleanup();
+ }, () => {
+ // Prevent the response promise from being reported as an
+ // unchecked rejection if the startup promise fails.
+ responsePromise.catch(() => {});
+
+ this._cleanup();
+ });
+
+ return result;
+ }
+};
+
+XPCOMUtils.defineLazyPreferenceGetter(NativeApp, "maxRead", PREF_MAX_READ, MAX_READ);
+XPCOMUtils.defineLazyPreferenceGetter(NativeApp, "maxWrite", PREF_MAX_WRITE, MAX_WRITE);
diff --git a/toolkit/components/webextensions/Schemas.jsm b/toolkit/components/webextensions/Schemas.jsm
new file mode 100644
index 000000000..159211c79
--- /dev/null
+++ b/toolkit/components/webextensions/Schemas.jsm
@@ -0,0 +1,2143 @@
+/* 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";
+
+const Ci = Components.interfaces;
+const Cc = Components.classes;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+const global = this;
+
+Cu.importGlobalProperties(["URL"]);
+
+Cu.import("resource://gre/modules/NetUtil.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ DefaultMap,
+ instanceOf,
+} = ExtensionUtils;
+
+class DeepMap extends DefaultMap {
+ constructor() {
+ super(() => new DeepMap());
+ }
+
+ getPath(...keys) {
+ return keys.reduce((map, prop) => map.get(prop), this);
+ }
+}
+
+XPCOMUtils.defineLazyServiceGetter(this, "contentPolicyService",
+ "@mozilla.org/addons/content-policy;1",
+ "nsIAddonContentPolicy");
+
+this.EXPORTED_SYMBOLS = ["Schemas"];
+
+/* globals Schemas, URL */
+
+function readJSON(url) {
+ return new Promise((resolve, reject) => {
+ NetUtil.asyncFetch({uri: url, loadUsingSystemPrincipal: true}, (inputStream, status) => {
+ if (!Components.isSuccessCode(status)) {
+ // Convert status code to a string
+ let e = Components.Exception("", status);
+ reject(new Error(`Error while loading '${url}' (${e.name})`));
+ return;
+ }
+ try {
+ let text = NetUtil.readInputStreamToString(inputStream, inputStream.available());
+
+ // Chrome JSON files include a license comment that we need to
+ // strip off for this to be valid JSON. As a hack, we just
+ // look for the first '[' character, which signals the start
+ // of the JSON content.
+ let index = text.indexOf("[");
+ text = text.slice(index);
+
+ resolve(JSON.parse(text));
+ } catch (e) {
+ reject(e);
+ }
+ });
+ });
+}
+
+/**
+ * Defines a lazy getter for the given property on the given object. Any
+ * security wrappers are waived on the object before the property is
+ * defined, and the getter and setter methods are wrapped for the target
+ * scope.
+ *
+ * The given getter function is guaranteed to be called only once, even
+ * if the target scope retrieves the wrapped getter from the property
+ * descriptor and calls it directly.
+ *
+ * @param {object} object
+ * The object on which to define the getter.
+ * @param {string|Symbol} prop
+ * The property name for which to define the getter.
+ * @param {function} getter
+ * The function to call in order to generate the final property
+ * value.
+ */
+function exportLazyGetter(object, prop, getter) {
+ object = Cu.waiveXrays(object);
+
+ let redefine = value => {
+ if (value === undefined) {
+ delete object[prop];
+ } else {
+ Object.defineProperty(object, prop, {
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ value,
+ });
+ }
+
+ getter = null;
+
+ return value;
+ };
+
+ Object.defineProperty(object, prop, {
+ enumerable: true,
+ configurable: true,
+
+ get: Cu.exportFunction(function() {
+ return redefine(getter.call(this));
+ }, object),
+
+ set: Cu.exportFunction(value => {
+ redefine(value);
+ }, object),
+ });
+}
+
+const POSTPROCESSORS = {
+ convertImageDataToURL(imageData, context) {
+ let document = context.cloneScope.document;
+ let canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
+ canvas.width = imageData.width;
+ canvas.height = imageData.height;
+ canvas.getContext("2d").putImageData(imageData, 0, 0);
+
+ return canvas.toDataURL("image/png");
+ },
+};
+
+// Parses a regular expression, with support for the Python extended
+// syntax that allows setting flags by including the string (?im)
+function parsePattern(pattern) {
+ let flags = "";
+ let match = /^\(\?([im]*)\)(.*)/.exec(pattern);
+ if (match) {
+ [, flags, pattern] = match;
+ }
+ return new RegExp(pattern, flags);
+}
+
+function getValueBaseType(value) {
+ let t = typeof(value);
+ if (t == "object") {
+ if (value === null) {
+ return "null";
+ } else if (Array.isArray(value)) {
+ return "array";
+ } else if (Object.prototype.toString.call(value) == "[object ArrayBuffer]") {
+ return "binary";
+ }
+ } else if (t == "number") {
+ if (value % 1 == 0) {
+ return "integer";
+ }
+ }
+ return t;
+}
+
+// Methods of Context that are used by Schemas.normalize. These methods can be
+// overridden at the construction of Context.
+const CONTEXT_FOR_VALIDATION = [
+ "checkLoadURL",
+ "hasPermission",
+ "logError",
+];
+
+// Methods of Context that are used by Schemas.inject.
+// Callers of Schemas.inject should implement all of these methods.
+const CONTEXT_FOR_INJECTION = [
+ ...CONTEXT_FOR_VALIDATION,
+ "shouldInject",
+ "getImplementation",
+];
+
+/**
+ * A context for schema validation and error reporting. This class is only used
+ * internally within Schemas.
+ */
+class Context {
+ /**
+ * @param {object} params Provides the implementation of this class.
+ * @param {Array<string>} overridableMethods
+ */
+ constructor(params, overridableMethods = CONTEXT_FOR_VALIDATION) {
+ this.params = params;
+
+ this.path = [];
+ this.preprocessors = {
+ localize(value, context) {
+ return value;
+ },
+ };
+ this.postprocessors = POSTPROCESSORS;
+ this.isChromeCompat = false;
+
+ this.currentChoices = new Set();
+ this.choicePathIndex = 0;
+
+ for (let method of overridableMethods) {
+ if (method in params) {
+ this[method] = params[method].bind(params);
+ }
+ }
+
+ let props = ["preprocessors", "isChromeCompat"];
+ for (let prop of props) {
+ if (prop in params) {
+ if (prop in this && typeof this[prop] == "object") {
+ Object.assign(this[prop], params[prop]);
+ } else {
+ this[prop] = params[prop];
+ }
+ }
+ }
+ }
+
+ get choicePath() {
+ let path = this.path.slice(this.choicePathIndex);
+ return path.join(".");
+ }
+
+ get cloneScope() {
+ return this.params.cloneScope;
+ }
+
+ get url() {
+ return this.params.url;
+ }
+
+ get principal() {
+ return this.params.principal || Services.scriptSecurityManager.createNullPrincipal({});
+ }
+
+ /**
+ * Checks whether `url` may be loaded by the extension in this context.
+ *
+ * @param {string} url The URL that the extension wished to load.
+ * @returns {boolean} Whether the context may load `url`.
+ */
+ checkLoadURL(url) {
+ let ssm = Services.scriptSecurityManager;
+ try {
+ ssm.checkLoadURIStrWithPrincipal(this.principal, url,
+ ssm.DISALLOW_INHERIT_PRINCIPAL);
+ } catch (e) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Checks whether this context has the given permission.
+ *
+ * @param {string} permission
+ * The name of the permission to check.
+ *
+ * @returns {boolean} True if the context has the given permission.
+ */
+ hasPermission(permission) {
+ return false;
+ }
+
+ /**
+ * Returns an error result object with the given message, for return
+ * by Type normalization functions.
+ *
+ * If the context has a `currentTarget` value, this is prepended to
+ * the message to indicate the location of the error.
+ *
+ * @param {string} errorMessage
+ * The error message which will be displayed when this is the
+ * only possible matching schema.
+ * @param {string} choicesMessage
+ * The message describing the valid what constitutes a valid
+ * value for this schema, which will be displayed when multiple
+ * schema choices are available and none match.
+ *
+ * A caller may pass `null` to prevent a choice from being
+ * added, but this should *only* be done from code processing a
+ * choices type.
+ * @returns {object}
+ */
+ error(errorMessage, choicesMessage = undefined) {
+ if (choicesMessage !== null) {
+ let {choicePath} = this;
+ if (choicePath) {
+ choicesMessage = `.${choicePath} must ${choicesMessage}`;
+ }
+
+ this.currentChoices.add(choicesMessage);
+ }
+
+ if (this.currentTarget) {
+ return {error: `Error processing ${this.currentTarget}: ${errorMessage}`};
+ }
+ return {error: errorMessage};
+ }
+
+ /**
+ * Creates an `Error` object belonging to the current unprivileged
+ * scope. If there is no unprivileged scope associated with this
+ * context, the message is returned as a string.
+ *
+ * If the context has a `currentTarget` value, this is prepended to
+ * the message, in the same way as for the `error` method.
+ *
+ * @param {string} message
+ * @returns {Error}
+ */
+ makeError(message) {
+ let {error} = this.error(message);
+ if (this.cloneScope) {
+ return new this.cloneScope.Error(error);
+ }
+ return error;
+ }
+
+ /**
+ * Logs the given error to the console. May be overridden to enable
+ * custom logging.
+ *
+ * @param {Error|string} error
+ */
+ logError(error) {
+ Cu.reportError(error);
+ }
+
+ /**
+ * Returns the name of the value currently being normalized. For a
+ * nested object, this is usually approximately equivalent to the
+ * JavaScript property accessor for that property. Given:
+ *
+ * { foo: { bar: [{ baz: x }] } }
+ *
+ * When processing the value for `x`, the currentTarget is
+ * 'foo.bar.0.baz'
+ */
+ get currentTarget() {
+ return this.path.join(".");
+ }
+
+ /**
+ * Executes the given callback, and returns an array of choice strings
+ * passed to {@see #error} during its execution.
+ *
+ * @param {function} callback
+ * @returns {object}
+ * An object with a `result` property containing the return
+ * value of the callback, and a `choice` property containing
+ * an array of choices.
+ */
+ withChoices(callback) {
+ let {currentChoices, choicePathIndex} = this;
+
+ let choices = new Set();
+ this.currentChoices = choices;
+ this.choicePathIndex = this.path.length;
+
+ try {
+ let result = callback();
+
+ return {result, choices: Array.from(choices)};
+ } finally {
+ this.currentChoices = currentChoices;
+ this.choicePathIndex = choicePathIndex;
+
+ choices = Array.from(choices);
+ if (choices.length == 1) {
+ currentChoices.add(choices[0]);
+ } else if (choices.length) {
+ let n = choices.length - 1;
+ choices[n] = `or ${choices[n]}`;
+
+ this.error(null, `must either [${choices.join(", ")}]`);
+ }
+ }
+ }
+
+ /**
+ * Appends the given component to the `currentTarget` path to indicate
+ * that it is being processed, calls the given callback function, and
+ * then restores the original path.
+ *
+ * This is used to identify the path of the property being processed
+ * when reporting type errors.
+ *
+ * @param {string} component
+ * @param {function} callback
+ * @returns {*}
+ */
+ withPath(component, callback) {
+ this.path.push(component);
+ try {
+ return callback();
+ } finally {
+ this.path.pop();
+ }
+ }
+}
+
+/**
+ * Holds methods that run the actual implementation of the extension APIs. These
+ * methods are only called if the extension API invocation matches the signature
+ * as defined in the schema. Otherwise an error is reported to the context.
+ */
+class InjectionContext extends Context {
+ constructor(params) {
+ super(params, CONTEXT_FOR_INJECTION);
+ }
+
+ /**
+ * Check whether the API should be injected.
+ *
+ * @abstract
+ * @param {string} namespace The namespace of the API. This may contain dots,
+ * e.g. in the case of "devtools.inspectedWindow".
+ * @param {string} [name] The name of the property in the namespace.
+ * `null` if we are checking whether the namespace should be injected.
+ * @param {Array<string>} allowedContexts A list of additional contexts in which
+ * this API should be available. May include any of:
+ * "main" - The main chrome browser process.
+ * "addon" - An addon process.
+ * "content" - A content process.
+ * @returns {boolean} Whether the API should be injected.
+ */
+ shouldInject(namespace, name, allowedContexts) {
+ throw new Error("Not implemented");
+ }
+
+ /**
+ * Generate the implementation for `namespace`.`name`.
+ *
+ * @abstract
+ * @param {string} namespace The full path to the namespace of the API, minus
+ * the name of the method or property. E.g. "storage.local".
+ * @param {string} name The name of the method, property or event.
+ * @returns {SchemaAPIInterface} The implementation of the API.
+ */
+ getImplementation(namespace, name) {
+ throw new Error("Not implemented");
+ }
+}
+
+/**
+ * The methods in this singleton represent the "format" specifier for
+ * JSON Schema string types.
+ *
+ * Each method either returns a normalized version of the original
+ * value, or throws an error if the value is not valid for the given
+ * format.
+ */
+const FORMATS = {
+ url(string, context) {
+ let url = new URL(string).href;
+
+ if (!context.checkLoadURL(url)) {
+ throw new Error(`Access denied for URL ${url}`);
+ }
+ return url;
+ },
+
+ relativeUrl(string, context) {
+ if (!context.url) {
+ // If there's no context URL, return relative URLs unresolved, and
+ // skip security checks for them.
+ try {
+ new URL(string);
+ } catch (e) {
+ return string;
+ }
+ }
+
+ let url = new URL(string, context.url).href;
+
+ if (!context.checkLoadURL(url)) {
+ throw new Error(`Access denied for URL ${url}`);
+ }
+ return url;
+ },
+
+ strictRelativeUrl(string, context) {
+ // Do not accept a string which resolves as an absolute URL, or any
+ // protocol-relative URL.
+ if (!string.startsWith("//")) {
+ try {
+ new URL(string);
+ } catch (e) {
+ return FORMATS.relativeUrl(string, context);
+ }
+ }
+
+ throw new SyntaxError(`String ${JSON.stringify(string)} must be a relative URL`);
+ },
+
+ contentSecurityPolicy(string, context) {
+ let error = contentPolicyService.validateAddonCSP(string);
+ if (error != null) {
+ throw new SyntaxError(error);
+ }
+ return string;
+ },
+
+ date(string, context) {
+ // A valid ISO 8601 timestamp.
+ const PATTERN = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|([-+]\d{2}:?\d{2})))?$/;
+ if (!PATTERN.test(string)) {
+ throw new Error(`Invalid date string ${string}`);
+ }
+ // Our pattern just checks the format, we could still have invalid
+ // values (e.g., month=99 or month=02 and day=31). Let the Date
+ // constructor do the dirty work of validating.
+ if (isNaN(new Date(string))) {
+ throw new Error(`Invalid date string ${string}`);
+ }
+ return string;
+ },
+};
+
+// Schema files contain namespaces, and each namespace contains types,
+// properties, functions, and events. An Entry is a base class for
+// types, properties, functions, and events.
+class Entry {
+ constructor(schema = {}) {
+ /**
+ * If set to any value which evaluates as true, this entry is
+ * deprecated, and any access to it will result in a deprecation
+ * warning being logged to the browser console.
+ *
+ * If the value is a string, it will be appended to the deprecation
+ * message. If it contains the substring "${value}", it will be
+ * replaced with a string representation of the value being
+ * processed.
+ *
+ * If the value is any other truthy value, a generic deprecation
+ * message will be emitted.
+ */
+ this.deprecated = false;
+ if ("deprecated" in schema) {
+ this.deprecated = schema.deprecated;
+ }
+
+ /**
+ * @property {string} [preprocessor]
+ * If set to a string value, and a preprocessor of the same is
+ * defined in the validation context, it will be applied to this
+ * value prior to any normalization.
+ */
+ this.preprocessor = schema.preprocess || null;
+
+ /**
+ * @property {string} [postprocessor]
+ * If set to a string value, and a postprocessor of the same is
+ * defined in the validation context, it will be applied to this
+ * value after any normalization.
+ */
+ this.postprocessor = schema.postprocess || null;
+
+ /**
+ * @property {Array<string>} allowedContexts A list of allowed contexts
+ * to consider before generating the API.
+ * These are not parsed by the schema, but passed to `shouldInject`.
+ */
+ this.allowedContexts = schema.allowedContexts || [];
+ }
+
+ /**
+ * Preprocess the given value with the preprocessor declared in
+ * `preprocessor`.
+ *
+ * @param {*} value
+ * @param {Context} context
+ * @returns {*}
+ */
+ preprocess(value, context) {
+ if (this.preprocessor) {
+ return context.preprocessors[this.preprocessor](value, context);
+ }
+ return value;
+ }
+
+ /**
+ * Postprocess the given result with the postprocessor declared in
+ * `postprocessor`.
+ *
+ * @param {object} result
+ * @param {Context} context
+ * @returns {object}
+ */
+ postprocess(result, context) {
+ if (result.error || !this.postprocessor) {
+ return result;
+ }
+
+ let value = context.postprocessors[this.postprocessor](result.value, context);
+ return {value};
+ }
+
+ /**
+ * Logs a deprecation warning for this entry, based on the value of
+ * its `deprecated` property.
+ *
+ * @param {Context} context
+ * @param {value} [value]
+ */
+ logDeprecation(context, value = null) {
+ let message = "This property is deprecated";
+ if (typeof(this.deprecated) == "string") {
+ message = this.deprecated;
+ if (message.includes("${value}")) {
+ try {
+ value = JSON.stringify(value);
+ } catch (e) {
+ value = String(value);
+ }
+ message = message.replace(/\$\{value\}/g, () => value);
+ }
+ }
+
+ context.logError(context.makeError(message));
+ }
+
+ /**
+ * Checks whether the entry is deprecated and, if so, logs a
+ * deprecation message.
+ *
+ * @param {Context} context
+ * @param {value} [value]
+ */
+ checkDeprecated(context, value = null) {
+ if (this.deprecated) {
+ this.logDeprecation(context, value);
+ }
+ }
+
+ /**
+ * Injects JS values for the entry into the extension API
+ * namespace. The default implementation is to do nothing.
+ * `context` is used to call the actual implementation
+ * of a given function or event.
+ *
+ * @param {Array<string>} path The API path, e.g. `["storage", "local"]`.
+ * @param {string} name The method name, e.g. "get".
+ * @param {object} dest The object where `path`.`name` should be stored.
+ * @param {InjectionContext} context
+ */
+ inject(path, name, dest, context) {
+ }
+}
+
+// Corresponds either to a type declared in the "types" section of the
+// schema or else to any type object used throughout the schema.
+class Type extends Entry {
+ /**
+ * @property {Array<string>} EXTRA_PROPERTIES
+ * An array of extra properties which may be present for
+ * schemas of this type.
+ */
+ static get EXTRA_PROPERTIES() {
+ return ["description", "deprecated", "preprocess", "postprocess", "allowedContexts"];
+ }
+
+ /**
+ * Parses the given schema object and returns an instance of this
+ * class which corresponds to its properties.
+ *
+ * @param {object} schema
+ * A JSON schema object which corresponds to a definition of
+ * this type.
+ * @param {Array<string>} path
+ * The path to this schema object from the root schema,
+ * corresponding to the property names and array indices
+ * traversed during parsing in order to arrive at this schema
+ * object.
+ * @param {Array<string>} [extraProperties]
+ * An array of extra property names which are valid for this
+ * schema in the current context.
+ * @returns {Type}
+ * An instance of this type which corresponds to the given
+ * schema object.
+ * @static
+ */
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ return new this(schema);
+ }
+
+ /**
+ * Checks that all of the properties present in the given schema
+ * object are valid properties for this type, and throws if invalid.
+ *
+ * @param {object} schema
+ * A JSON schema object.
+ * @param {Array<string>} path
+ * The path to this schema object from the root schema,
+ * corresponding to the property names and array indices
+ * traversed during parsing in order to arrive at this schema
+ * object.
+ * @param {Array<string>} [extra]
+ * An array of extra property names which are valid for this
+ * schema in the current context.
+ * @throws {Error}
+ * An error describing the first invalid property found in the
+ * schema object.
+ */
+ static checkSchemaProperties(schema, path, extra = []) {
+ let allowedSet = new Set([...this.EXTRA_PROPERTIES, ...extra]);
+
+ for (let prop of Object.keys(schema)) {
+ if (!allowedSet.has(prop)) {
+ throw new Error(`Internal error: Namespace ${path.join(".")} has invalid type property "${prop}" in type "${schema.id || JSON.stringify(schema)}"`);
+ }
+ }
+ }
+
+ // Takes a value, checks that it has the correct type, and returns a
+ // "normalized" version of the value. The normalized version will
+ // include "nulls" in place of omitted optional properties. The
+ // result of this function is either {error: "Some type error"} or
+ // {value: <normalized-value>}.
+ normalize(value, context) {
+ return context.error("invalid type");
+ }
+
+ // Unlike normalize, this function does a shallow check to see if
+ // |baseType| (one of the possible getValueBaseType results) is
+ // valid for this type. It returns true or false. It's used to fill
+ // in optional arguments to functions before actually type checking
+
+ checkBaseType(baseType) {
+ return false;
+ }
+
+ // Helper method that simply relies on checkBaseType to implement
+ // normalize. Subclasses can choose to use it or not.
+ normalizeBase(type, value, context) {
+ if (this.checkBaseType(getValueBaseType(value))) {
+ this.checkDeprecated(context, value);
+ return {value: this.preprocess(value, context)};
+ }
+
+ let choice;
+ if (/^[aeiou]/.test(type)) {
+ choice = `be an ${type} value`;
+ } else {
+ choice = `be a ${type} value`;
+ }
+
+ return context.error(`Expected ${type} instead of ${JSON.stringify(value)}`,
+ choice);
+ }
+}
+
+// Type that allows any value.
+class AnyType extends Type {
+ normalize(value, context) {
+ this.checkDeprecated(context, value);
+ return this.postprocess({value}, context);
+ }
+
+ checkBaseType(baseType) {
+ return true;
+ }
+}
+
+// An untagged union type.
+class ChoiceType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["choices", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let choices = schema.choices.map(t => Schemas.parseSchema(t, path));
+ return new this(schema, choices);
+ }
+
+ constructor(schema, choices) {
+ super(schema);
+ this.choices = choices;
+ }
+
+ extend(type) {
+ this.choices.push(...type.choices);
+
+ return this;
+ }
+
+ normalize(value, context) {
+ this.checkDeprecated(context, value);
+
+ let error;
+ let {choices, result} = context.withChoices(() => {
+ for (let choice of this.choices) {
+ let r = choice.normalize(value, context);
+ if (!r.error) {
+ return r;
+ }
+
+ error = r;
+ }
+ });
+
+ if (result) {
+ return result;
+ }
+ if (choices.length <= 1) {
+ return error;
+ }
+
+ let n = choices.length - 1;
+ choices[n] = `or ${choices[n]}`;
+
+ let message = `Value must either: ${choices.join(", ")}`;
+
+ return context.error(message, null);
+ }
+
+ checkBaseType(baseType) {
+ return this.choices.some(t => t.checkBaseType(baseType));
+ }
+}
+
+// This is a reference to another type--essentially a typedef.
+class RefType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["$ref", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let ref = schema.$ref;
+ let ns = path[0];
+ if (ref.includes(".")) {
+ [ns, ref] = ref.split(".");
+ }
+ return new this(schema, ns, ref);
+ }
+
+ // For a reference to a type named T declared in namespace NS,
+ // namespaceName will be NS and reference will be T.
+ constructor(schema, namespaceName, reference) {
+ super(schema);
+ this.namespaceName = namespaceName;
+ this.reference = reference;
+ }
+
+ get targetType() {
+ let ns = Schemas.namespaces.get(this.namespaceName);
+ let type = ns.get(this.reference);
+ if (!type) {
+ throw new Error(`Internal error: Type ${this.reference} not found`);
+ }
+ return type;
+ }
+
+ normalize(value, context) {
+ this.checkDeprecated(context, value);
+ return this.targetType.normalize(value, context);
+ }
+
+ checkBaseType(baseType) {
+ return this.targetType.checkBaseType(baseType);
+ }
+}
+
+class StringType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["enum", "minLength", "maxLength", "pattern", "format",
+ ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let enumeration = schema.enum || null;
+ if (enumeration) {
+ // The "enum" property is either a list of strings that are
+ // valid values or else a list of {name, description} objects,
+ // where the .name values are the valid values.
+ enumeration = enumeration.map(e => {
+ if (typeof(e) == "object") {
+ return e.name;
+ }
+ return e;
+ });
+ }
+
+ let pattern = null;
+ if (schema.pattern) {
+ try {
+ pattern = parsePattern(schema.pattern);
+ } catch (e) {
+ throw new Error(`Internal error: Invalid pattern ${JSON.stringify(schema.pattern)}`);
+ }
+ }
+
+ let format = null;
+ if (schema.format) {
+ if (!(schema.format in FORMATS)) {
+ throw new Error(`Internal error: Invalid string format ${schema.format}`);
+ }
+ format = FORMATS[schema.format];
+ }
+ return new this(schema, enumeration,
+ schema.minLength || 0,
+ schema.maxLength || Infinity,
+ pattern,
+ format);
+ }
+
+ constructor(schema, enumeration, minLength, maxLength, pattern, format) {
+ super(schema);
+ this.enumeration = enumeration;
+ this.minLength = minLength;
+ this.maxLength = maxLength;
+ this.pattern = pattern;
+ this.format = format;
+ }
+
+ normalize(value, context) {
+ let r = this.normalizeBase("string", value, context);
+ if (r.error) {
+ return r;
+ }
+ value = r.value;
+
+ if (this.enumeration) {
+ if (this.enumeration.includes(value)) {
+ return this.postprocess({value}, context);
+ }
+
+ let choices = this.enumeration.map(JSON.stringify).join(", ");
+
+ return context.error(`Invalid enumeration value ${JSON.stringify(value)}`,
+ `be one of [${choices}]`);
+ }
+
+ if (value.length < this.minLength) {
+ return context.error(`String ${JSON.stringify(value)} is too short (must be ${this.minLength})`,
+ `be longer than ${this.minLength}`);
+ }
+ if (value.length > this.maxLength) {
+ return context.error(`String ${JSON.stringify(value)} is too long (must be ${this.maxLength})`,
+ `be shorter than ${this.maxLength}`);
+ }
+
+ if (this.pattern && !this.pattern.test(value)) {
+ return context.error(`String ${JSON.stringify(value)} must match ${this.pattern}`,
+ `match the pattern ${this.pattern.toSource()}`);
+ }
+
+ if (this.format) {
+ try {
+ r.value = this.format(r.value, context);
+ } catch (e) {
+ return context.error(String(e), `match the format "${this.format.name}"`);
+ }
+ }
+
+ return r;
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "string";
+ }
+
+ inject(path, name, dest, context) {
+ if (this.enumeration) {
+ exportLazyGetter(dest, name, () => {
+ let obj = Cu.createObjectIn(dest);
+ for (let e of this.enumeration) {
+ obj[e.toUpperCase()] = e;
+ }
+ return obj;
+ });
+ }
+ }
+}
+
+let SubModuleType;
+class ObjectType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["properties", "patternProperties", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ if ("functions" in schema) {
+ return SubModuleType.parseSchema(schema, path, extraProperties);
+ }
+
+ if (!("$extend" in schema)) {
+ // Only allow extending "properties" and "patternProperties".
+ extraProperties = ["additionalProperties", "isInstanceOf", ...extraProperties];
+ }
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let parseProperty = (schema, extraProps = []) => {
+ return {
+ type: Schemas.parseSchema(schema, path,
+ ["unsupported", "onError", "permissions", ...extraProps]),
+ optional: schema.optional || false,
+ unsupported: schema.unsupported || false,
+ onError: schema.onError || null,
+ };
+ };
+
+ // Parse explicit "properties" object.
+ let properties = Object.create(null);
+ for (let propName of Object.keys(schema.properties || {})) {
+ properties[propName] = parseProperty(schema.properties[propName], ["optional"]);
+ }
+
+ // Parse regexp properties from "patternProperties" object.
+ let patternProperties = [];
+ for (let propName of Object.keys(schema.patternProperties || {})) {
+ let pattern;
+ try {
+ pattern = parsePattern(propName);
+ } catch (e) {
+ throw new Error(`Internal error: Invalid property pattern ${JSON.stringify(propName)}`);
+ }
+
+ patternProperties.push({
+ pattern,
+ type: parseProperty(schema.patternProperties[propName]),
+ });
+ }
+
+ // Parse "additionalProperties" schema.
+ let additionalProperties = null;
+ if (schema.additionalProperties) {
+ let type = schema.additionalProperties;
+ if (type === true) {
+ type = {"type": "any"};
+ }
+
+ additionalProperties = Schemas.parseSchema(type, path);
+ }
+
+ return new this(schema, properties, additionalProperties, patternProperties, schema.isInstanceOf || null);
+ }
+
+ constructor(schema, properties, additionalProperties, patternProperties, isInstanceOf) {
+ super(schema);
+ this.properties = properties;
+ this.additionalProperties = additionalProperties;
+ this.patternProperties = patternProperties;
+ this.isInstanceOf = isInstanceOf;
+ }
+
+ extend(type) {
+ for (let key of Object.keys(type.properties)) {
+ if (key in this.properties) {
+ throw new Error(`InternalError: Attempt to extend an object with conflicting property "${key}"`);
+ }
+ this.properties[key] = type.properties[key];
+ }
+
+ this.patternProperties.push(...type.patternProperties);
+
+ return this;
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "object";
+ }
+
+ /**
+ * Extracts the enumerable properties of the given object, including
+ * function properties which would normally be omitted by X-ray
+ * wrappers.
+ *
+ * @param {object} value
+ * @param {Context} context
+ * The current parse context.
+ * @returns {object}
+ * An object with an `error` or `value` property.
+ */
+ extractProperties(value, context) {
+ // |value| should be a JS Xray wrapping an object in the
+ // extension compartment. This works well except when we need to
+ // access callable properties on |value| since JS Xrays don't
+ // support those. To work around the problem, we verify that
+ // |value| is a plain JS object (i.e., not anything scary like a
+ // Proxy). Then we copy the properties out of it into a normal
+ // object using a waiver wrapper.
+
+ let klass = Cu.getClassName(value, true);
+ if (klass != "Object") {
+ throw context.error(`Expected a plain JavaScript object, got a ${klass}`,
+ `be a plain JavaScript object`);
+ }
+
+ let properties = Object.create(null);
+
+ let waived = Cu.waiveXrays(value);
+ for (let prop of Object.getOwnPropertyNames(waived)) {
+ let desc = Object.getOwnPropertyDescriptor(waived, prop);
+ if (desc.get || desc.set) {
+ throw context.error("Objects cannot have getters or setters on properties",
+ "contain no getter or setter properties");
+ }
+ // Chrome ignores non-enumerable properties.
+ if (desc.enumerable) {
+ properties[prop] = Cu.unwaiveXrays(desc.value);
+ }
+ }
+
+ return properties;
+ }
+
+ checkProperty(context, prop, propType, result, properties, remainingProps) {
+ let {type, optional, unsupported, onError} = propType;
+ let error = null;
+
+ if (unsupported) {
+ if (prop in properties) {
+ error = context.error(`Property "${prop}" is unsupported by Firefox`,
+ `not contain an unsupported "${prop}" property`);
+ }
+ } else if (prop in properties) {
+ if (optional && (properties[prop] === null || properties[prop] === undefined)) {
+ result[prop] = null;
+ } else {
+ let r = context.withPath(prop, () => type.normalize(properties[prop], context));
+ if (r.error) {
+ error = r;
+ } else {
+ result[prop] = r.value;
+ properties[prop] = r.value;
+ }
+ }
+ remainingProps.delete(prop);
+ } else if (!optional) {
+ error = context.error(`Property "${prop}" is required`,
+ `contain the required "${prop}" property`);
+ } else if (optional !== "omit-key-if-missing") {
+ result[prop] = null;
+ }
+
+ if (error) {
+ if (onError == "warn") {
+ context.logError(error.error);
+ } else if (onError != "ignore") {
+ throw error;
+ }
+
+ result[prop] = null;
+ }
+ }
+
+ normalize(value, context) {
+ try {
+ let v = this.normalizeBase("object", value, context);
+ if (v.error) {
+ return v;
+ }
+ value = v.value;
+
+ if (this.isInstanceOf) {
+ if (Object.keys(this.properties).length ||
+ this.patternProperties.length ||
+ !(this.additionalProperties instanceof AnyType)) {
+ throw new Error("InternalError: isInstanceOf can only be used with objects that are otherwise unrestricted");
+ }
+
+ if (!instanceOf(value, this.isInstanceOf)) {
+ return context.error(`Object must be an instance of ${this.isInstanceOf}`,
+ `be an instance of ${this.isInstanceOf}`);
+ }
+
+ // This is kind of a hack, but we can't normalize things that
+ // aren't JSON, so we just return them.
+ return this.postprocess({value}, context);
+ }
+
+ let properties = this.extractProperties(value, context);
+ let remainingProps = new Set(Object.keys(properties));
+
+ let result = {};
+ for (let prop of Object.keys(this.properties)) {
+ this.checkProperty(context, prop, this.properties[prop], result,
+ properties, remainingProps);
+ }
+
+ for (let prop of Object.keys(properties)) {
+ for (let {pattern, type} of this.patternProperties) {
+ if (pattern.test(prop)) {
+ this.checkProperty(context, prop, type, result,
+ properties, remainingProps);
+ }
+ }
+ }
+
+ if (this.additionalProperties) {
+ for (let prop of remainingProps) {
+ let type = this.additionalProperties;
+ let r = context.withPath(prop, () => type.normalize(properties[prop], context));
+ if (r.error) {
+ return r;
+ }
+ result[prop] = r.value;
+ }
+ } else if (remainingProps.size == 1) {
+ return context.error(`Unexpected property "${[...remainingProps]}"`,
+ `not contain an unexpected "${[...remainingProps]}" property`);
+ } else if (remainingProps.size) {
+ let props = [...remainingProps].sort().join(", ");
+ return context.error(`Unexpected properties: ${props}`,
+ `not contain the unexpected properties [${props}]`);
+ }
+
+ return this.postprocess({value: result}, context);
+ } catch (e) {
+ if (e.error) {
+ return e;
+ }
+ throw e;
+ }
+ }
+}
+
+// This type is just a placeholder to be referred to by
+// SubModuleProperty. No value is ever expected to have this type.
+SubModuleType = class SubModuleType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["functions", "events", "properties", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ // The path we pass in here is only used for error messages.
+ path = [...path, schema.id];
+ let functions = schema.functions.map(fun => Schemas.parseFunction(path, fun));
+
+ return new this(functions);
+ }
+
+ constructor(functions) {
+ super();
+ this.functions = functions;
+ }
+};
+
+class NumberType extends Type {
+ normalize(value, context) {
+ let r = this.normalizeBase("number", value, context);
+ if (r.error) {
+ return r;
+ }
+
+ if (isNaN(r.value) || !Number.isFinite(r.value)) {
+ return context.error("NaN and infinity are not valid",
+ "be a finite number");
+ }
+
+ return r;
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "number" || baseType == "integer";
+ }
+}
+
+class IntegerType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["minimum", "maximum", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ return new this(schema, schema.minimum || -Infinity, schema.maximum || Infinity);
+ }
+
+ constructor(schema, minimum, maximum) {
+ super(schema);
+ this.minimum = minimum;
+ this.maximum = maximum;
+ }
+
+ normalize(value, context) {
+ let r = this.normalizeBase("integer", value, context);
+ if (r.error) {
+ return r;
+ }
+ value = r.value;
+
+ // Ensure it's between -2**31 and 2**31-1
+ if (!Number.isSafeInteger(value)) {
+ return context.error("Integer is out of range",
+ "be a valid 32 bit signed integer");
+ }
+
+ if (value < this.minimum) {
+ return context.error(`Integer ${value} is too small (must be at least ${this.minimum})`,
+ `be at least ${this.minimum}`);
+ }
+ if (value > this.maximum) {
+ return context.error(`Integer ${value} is too big (must be at most ${this.maximum})`,
+ `be no greater than ${this.maximum}`);
+ }
+
+ return this.postprocess(r, context);
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "integer";
+ }
+}
+
+class BooleanType extends Type {
+ normalize(value, context) {
+ return this.normalizeBase("boolean", value, context);
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "boolean";
+ }
+}
+
+class ArrayType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["items", "minItems", "maxItems", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let items = Schemas.parseSchema(schema.items, path);
+
+ return new this(schema, items, schema.minItems || 0, schema.maxItems || Infinity);
+ }
+
+ constructor(schema, itemType, minItems, maxItems) {
+ super(schema);
+ this.itemType = itemType;
+ this.minItems = minItems;
+ this.maxItems = maxItems;
+ }
+
+ normalize(value, context) {
+ let v = this.normalizeBase("array", value, context);
+ if (v.error) {
+ return v;
+ }
+ value = v.value;
+
+ let result = [];
+ for (let [i, element] of value.entries()) {
+ element = context.withPath(String(i), () => this.itemType.normalize(element, context));
+ if (element.error) {
+ return element;
+ }
+ result.push(element.value);
+ }
+
+ if (result.length < this.minItems) {
+ return context.error(`Array requires at least ${this.minItems} items; you have ${result.length}`,
+ `have at least ${this.minItems} items`);
+ }
+
+ if (result.length > this.maxItems) {
+ return context.error(`Array requires at most ${this.maxItems} items; you have ${result.length}`,
+ `have at most ${this.maxItems} items`);
+ }
+
+ return this.postprocess({value: result}, context);
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "array";
+ }
+}
+
+class FunctionType extends Type {
+ static get EXTRA_PROPERTIES() {
+ return ["parameters", "async", "returns", ...super.EXTRA_PROPERTIES];
+ }
+
+ static parseSchema(schema, path, extraProperties = []) {
+ this.checkSchemaProperties(schema, path, extraProperties);
+
+ let isAsync = !!schema.async;
+ let isExpectingCallback = typeof schema.async === "string";
+ let parameters = null;
+ if ("parameters" in schema) {
+ parameters = [];
+ for (let param of schema.parameters) {
+ // Callbacks default to optional for now, because of promise
+ // handling.
+ let isCallback = isAsync && param.name == schema.async;
+ if (isCallback) {
+ isExpectingCallback = false;
+ }
+
+ parameters.push({
+ type: Schemas.parseSchema(param, path, ["name", "optional", "default"]),
+ name: param.name,
+ optional: param.optional == null ? isCallback : param.optional,
+ default: param.default == undefined ? null : param.default,
+ });
+ }
+ }
+ if (isExpectingCallback) {
+ throw new Error(`Internal error: Expected a callback parameter with name ${schema.async}`);
+ }
+
+ let hasAsyncCallback = false;
+ if (isAsync) {
+ hasAsyncCallback = (parameters &&
+ parameters.length &&
+ parameters[parameters.length - 1].name == schema.async);
+
+ if (schema.returns) {
+ throw new Error("Internal error: Async functions must not have return values.");
+ }
+ if (schema.allowAmbiguousOptionalArguments && !hasAsyncCallback) {
+ throw new Error("Internal error: Async functions with ambiguous arguments must declare the callback as the last parameter");
+ }
+ }
+
+ return new this(schema, parameters, isAsync, hasAsyncCallback);
+ }
+
+ constructor(schema, parameters, isAsync, hasAsyncCallback) {
+ super(schema);
+ this.parameters = parameters;
+ this.isAsync = isAsync;
+ this.hasAsyncCallback = hasAsyncCallback;
+ }
+
+ normalize(value, context) {
+ return this.normalizeBase("function", value, context);
+ }
+
+ checkBaseType(baseType) {
+ return baseType == "function";
+ }
+}
+
+// Represents a "property" defined in a schema namespace with a
+// particular value. Essentially this is a constant.
+class ValueProperty extends Entry {
+ constructor(schema, name, value) {
+ super(schema);
+ this.name = name;
+ this.value = value;
+ }
+
+ inject(path, name, dest, context) {
+ dest[name] = this.value;
+ }
+}
+
+// Represents a "property" defined in a schema namespace that is not a
+// constant.
+class TypeProperty extends Entry {
+ constructor(schema, namespaceName, name, type, writable) {
+ super(schema);
+ this.namespaceName = namespaceName;
+ this.name = name;
+ this.type = type;
+ this.writable = writable;
+ }
+
+ throwError(context, msg) {
+ throw context.makeError(`${msg} for ${this.namespaceName}.${this.name}.`);
+ }
+
+ inject(path, name, dest, context) {
+ if (this.unsupported) {
+ return;
+ }
+
+ let apiImpl = context.getImplementation(path.join("."), name);
+
+ let getStub = () => {
+ this.checkDeprecated(context);
+ return apiImpl.getProperty();
+ };
+
+ let desc = {
+ configurable: false,
+ enumerable: true,
+
+ get: Cu.exportFunction(getStub, dest),
+ };
+
+ if (this.writable) {
+ let setStub = (value) => {
+ let normalized = this.type.normalize(value, context);
+ if (normalized.error) {
+ this.throwError(context, normalized.error);
+ }
+
+ apiImpl.setProperty(normalized.value);
+ };
+
+ desc.set = Cu.exportFunction(setStub, dest);
+ }
+
+ Object.defineProperty(dest, name, desc);
+ }
+}
+
+class SubModuleProperty extends Entry {
+ // A SubModuleProperty represents a tree of objects and properties
+ // to expose to an extension. Currently we support only a limited
+ // form of sub-module properties, where "$ref" points to a
+ // SubModuleType containing a list of functions and "properties" is
+ // a list of additional simple properties.
+ //
+ // name: Name of the property stuff is being added to.
+ // namespaceName: Namespace in which the property lives.
+ // reference: Name of the type defining the functions to add to the property.
+ // properties: Additional properties to add to the module (unsupported).
+ constructor(schema, name, namespaceName, reference, properties) {
+ super(schema);
+ this.name = name;
+ this.namespaceName = namespaceName;
+ this.reference = reference;
+ this.properties = properties;
+ }
+
+ inject(path, name, dest, context) {
+ exportLazyGetter(dest, name, () => {
+ let obj = Cu.createObjectIn(dest);
+
+ let ns = Schemas.namespaces.get(this.namespaceName);
+ let type = ns.get(this.reference);
+ if (!type && this.reference.includes(".")) {
+ let [namespaceName, ref] = this.reference.split(".");
+ ns = Schemas.namespaces.get(namespaceName);
+ type = ns.get(ref);
+ }
+ if (!type || !(type instanceof SubModuleType)) {
+ throw new Error(`Internal error: ${this.namespaceName}.${this.reference} is not a sub-module`);
+ }
+
+ let functions = type.functions;
+ for (let fun of functions) {
+ let subpath = path.concat(name);
+ let namespace = subpath.join(".");
+ let allowedContexts = fun.allowedContexts.length ? fun.allowedContexts : ns.defaultContexts;
+ if (context.shouldInject(namespace, fun.name, allowedContexts)) {
+ fun.inject(subpath, fun.name, obj, context);
+ }
+ }
+
+ // TODO: Inject this.properties.
+
+ return obj;
+ });
+ }
+}
+
+// This class is a base class for FunctionEntrys and Events. It takes
+// care of validating parameter lists (i.e., handling of optional
+// parameters and parameter type checking).
+class CallEntry extends Entry {
+ constructor(schema, path, name, parameters, allowAmbiguousOptionalArguments) {
+ super(schema);
+ this.path = path;
+ this.name = name;
+ this.parameters = parameters;
+ this.allowAmbiguousOptionalArguments = allowAmbiguousOptionalArguments;
+ }
+
+ throwError(context, msg) {
+ throw context.makeError(`${msg} for ${this.path.join(".")}.${this.name}.`);
+ }
+
+ checkParameters(args, context) {
+ let fixedArgs = [];
+
+ // First we create a new array, fixedArgs, that is the same as
+ // |args| but with default values in place of omitted optional parameters.
+ let check = (parameterIndex, argIndex) => {
+ if (parameterIndex == this.parameters.length) {
+ if (argIndex == args.length) {
+ return true;
+ }
+ return false;
+ }
+
+ let parameter = this.parameters[parameterIndex];
+ if (parameter.optional) {
+ // Try skipping it.
+ fixedArgs[parameterIndex] = parameter.default;
+ if (check(parameterIndex + 1, argIndex)) {
+ return true;
+ }
+ }
+
+ if (argIndex == args.length) {
+ return false;
+ }
+
+ let arg = args[argIndex];
+ if (!parameter.type.checkBaseType(getValueBaseType(arg))) {
+ // For Chrome compatibility, use the default value if null or undefined
+ // is explicitly passed but is not a valid argument in this position.
+ if (parameter.optional && (arg === null || arg === undefined)) {
+ fixedArgs[parameterIndex] = Cu.cloneInto(parameter.default, global);
+ } else {
+ return false;
+ }
+ } else {
+ fixedArgs[parameterIndex] = arg;
+ }
+
+ return check(parameterIndex + 1, argIndex + 1);
+ };
+
+ if (this.allowAmbiguousOptionalArguments) {
+ // When this option is set, it's up to the implementation to
+ // parse arguments.
+ // The last argument for asynchronous methods is either a function or null.
+ // This is specifically done for runtime.sendMessage.
+ if (this.hasAsyncCallback && typeof(args[args.length - 1]) != "function") {
+ args.push(null);
+ }
+ return args;
+ }
+ let success = check(0, 0);
+ if (!success) {
+ this.throwError(context, "Incorrect argument types");
+ }
+
+ // Now we normalize (and fully type check) all non-omitted arguments.
+ fixedArgs = fixedArgs.map((arg, parameterIndex) => {
+ if (arg === null) {
+ return null;
+ }
+ let parameter = this.parameters[parameterIndex];
+ let r = parameter.type.normalize(arg, context);
+ if (r.error) {
+ this.throwError(context, `Type error for parameter ${parameter.name} (${r.error})`);
+ }
+ return r.value;
+ });
+
+ return fixedArgs;
+ }
+}
+
+// Represents a "function" defined in a schema namespace.
+class FunctionEntry extends CallEntry {
+ constructor(schema, path, name, type, unsupported, allowAmbiguousOptionalArguments, returns, permissions) {
+ super(schema, path, name, type.parameters, allowAmbiguousOptionalArguments);
+ this.unsupported = unsupported;
+ this.returns = returns;
+ this.permissions = permissions;
+
+ this.isAsync = type.isAsync;
+ this.hasAsyncCallback = type.hasAsyncCallback;
+ }
+
+ inject(path, name, dest, context) {
+ if (this.unsupported) {
+ return;
+ }
+
+ if (this.permissions && !this.permissions.some(perm => context.hasPermission(perm))) {
+ return;
+ }
+
+ exportLazyGetter(dest, name, () => {
+ let apiImpl = context.getImplementation(path.join("."), name);
+
+ let stub;
+ if (this.isAsync) {
+ stub = (...args) => {
+ this.checkDeprecated(context);
+ let actuals = this.checkParameters(args, context);
+ let callback = null;
+ if (this.hasAsyncCallback) {
+ callback = actuals.pop();
+ }
+ if (callback === null && context.isChromeCompat) {
+ // We pass an empty stub function as a default callback for
+ // the `chrome` API, so promise objects are not returned,
+ // and lastError values are reported immediately.
+ callback = () => {};
+ }
+ return apiImpl.callAsyncFunction(actuals, callback);
+ };
+ } else if (!this.returns) {
+ stub = (...args) => {
+ this.checkDeprecated(context);
+ let actuals = this.checkParameters(args, context);
+ return apiImpl.callFunctionNoReturn(actuals);
+ };
+ } else {
+ stub = (...args) => {
+ this.checkDeprecated(context);
+ let actuals = this.checkParameters(args, context);
+ return apiImpl.callFunction(actuals);
+ };
+ }
+ return Cu.exportFunction(stub, dest);
+ });
+ }
+}
+
+// Represents an "event" defined in a schema namespace.
+class Event extends CallEntry {
+ constructor(schema, path, name, type, extraParameters, unsupported, permissions) {
+ super(schema, path, name, extraParameters);
+ this.type = type;
+ this.unsupported = unsupported;
+ this.permissions = permissions;
+ }
+
+ checkListener(listener, context) {
+ let r = this.type.normalize(listener, context);
+ if (r.error) {
+ this.throwError(context, "Invalid listener");
+ }
+ return r.value;
+ }
+
+ inject(path, name, dest, context) {
+ if (this.unsupported) {
+ return;
+ }
+
+ if (this.permissions && !this.permissions.some(perm => context.hasPermission(perm))) {
+ return;
+ }
+
+ exportLazyGetter(dest, name, () => {
+ let apiImpl = context.getImplementation(path.join("."), name);
+
+ let addStub = (listener, ...args) => {
+ listener = this.checkListener(listener, context);
+ let actuals = this.checkParameters(args, context);
+ apiImpl.addListener(listener, actuals);
+ };
+
+ let removeStub = (listener) => {
+ listener = this.checkListener(listener, context);
+ apiImpl.removeListener(listener);
+ };
+
+ let hasStub = (listener) => {
+ listener = this.checkListener(listener, context);
+ return apiImpl.hasListener(listener);
+ };
+
+ let obj = Cu.createObjectIn(dest);
+
+ Cu.exportFunction(addStub, obj, {defineAs: "addListener"});
+ Cu.exportFunction(removeStub, obj, {defineAs: "removeListener"});
+ Cu.exportFunction(hasStub, obj, {defineAs: "hasListener"});
+
+ return obj;
+ });
+ }
+}
+
+const TYPES = Object.freeze(Object.assign(Object.create(null), {
+ any: AnyType,
+ array: ArrayType,
+ boolean: BooleanType,
+ function: FunctionType,
+ integer: IntegerType,
+ number: NumberType,
+ object: ObjectType,
+ string: StringType,
+}));
+
+this.Schemas = {
+ initialized: false,
+
+ // Maps a schema URL to the JSON contained in that schema file. This
+ // is useful for sending the JSON across processes.
+ schemaJSON: new Map(),
+
+ // Map[<schema-name> -> Map[<symbol-name> -> Entry]]
+ // This keeps track of all the schemas that have been loaded so far.
+ namespaces: new Map(),
+
+ register(namespaceName, symbol, value) {
+ let ns = this.namespaces.get(namespaceName);
+ if (!ns) {
+ ns = new Map();
+ ns.name = namespaceName;
+ ns.permissions = null;
+ ns.allowedContexts = [];
+ ns.defaultContexts = [];
+ this.namespaces.set(namespaceName, ns);
+ }
+ ns.set(symbol, value);
+ },
+
+ parseSchema(schema, path, extraProperties = []) {
+ let allowedProperties = new Set(extraProperties);
+
+ if ("choices" in schema) {
+ return ChoiceType.parseSchema(schema, path, allowedProperties);
+ } else if ("$ref" in schema) {
+ return RefType.parseSchema(schema, path, allowedProperties);
+ }
+
+ if (!("type" in schema)) {
+ throw new Error(`Unexpected value for type: ${JSON.stringify(schema)}`);
+ }
+
+ allowedProperties.add("type");
+
+ let type = TYPES[schema.type];
+ if (!type) {
+ throw new Error(`Unexpected type ${schema.type}`);
+ }
+ return type.parseSchema(schema, path, allowedProperties);
+ },
+
+ parseFunction(path, fun) {
+ let f = new FunctionEntry(fun, path, fun.name,
+ this.parseSchema(fun, path,
+ ["name", "unsupported", "returns",
+ "permissions",
+ "allowAmbiguousOptionalArguments"]),
+ fun.unsupported || false,
+ fun.allowAmbiguousOptionalArguments || false,
+ fun.returns || null,
+ fun.permissions || null);
+ return f;
+ },
+
+ loadType(namespaceName, type) {
+ if ("$extend" in type) {
+ this.extendType(namespaceName, type);
+ } else {
+ this.register(namespaceName, type.id, this.parseSchema(type, [namespaceName], ["id"]));
+ }
+ },
+
+ extendType(namespaceName, type) {
+ let ns = Schemas.namespaces.get(namespaceName);
+ let targetType = ns && ns.get(type.$extend);
+
+ // Only allow extending object and choices types for now.
+ if (targetType instanceof ObjectType) {
+ type.type = "object";
+ } else if (!targetType) {
+ throw new Error(`Internal error: Attempt to extend a nonexistant type ${type.$extend}`);
+ } else if (!(targetType instanceof ChoiceType)) {
+ throw new Error(`Internal error: Attempt to extend a non-extensible type ${type.$extend}`);
+ }
+
+ let parsed = this.parseSchema(type, [namespaceName], ["$extend"]);
+ if (parsed.constructor !== targetType.constructor) {
+ throw new Error(`Internal error: Bad attempt to extend ${type.$extend}`);
+ }
+
+ targetType.extend(parsed);
+ },
+
+ loadProperty(namespaceName, name, prop) {
+ if ("$ref" in prop) {
+ if (!prop.unsupported) {
+ this.register(namespaceName, name, new SubModuleProperty(prop, name, namespaceName, prop.$ref,
+ prop.properties || {}));
+ }
+ } else if ("value" in prop) {
+ this.register(namespaceName, name, new ValueProperty(prop, name, prop.value));
+ } else {
+ // We ignore the "optional" attribute on properties since we
+ // don't inject anything here anyway.
+ let type = this.parseSchema(prop, [namespaceName], ["optional", "writable"]);
+ this.register(namespaceName, name, new TypeProperty(prop, namespaceName, name, type, prop.writable || false));
+ }
+ },
+
+ loadFunction(namespaceName, fun) {
+ let f = this.parseFunction([namespaceName], fun);
+ this.register(namespaceName, fun.name, f);
+ },
+
+ loadEvent(namespaceName, event) {
+ let extras = event.extraParameters || [];
+ extras = extras.map(param => {
+ return {
+ type: this.parseSchema(param, [namespaceName], ["name", "optional", "default"]),
+ name: param.name,
+ optional: param.optional || false,
+ default: param.default == undefined ? null : param.default,
+ };
+ });
+
+ // We ignore these properties for now.
+ /* eslint-disable no-unused-vars */
+ let returns = event.returns;
+ let filters = event.filters;
+ /* eslint-enable no-unused-vars */
+
+ let type = this.parseSchema(event, [namespaceName],
+ ["name", "unsupported", "permissions",
+ "extraParameters", "returns", "filters"]);
+
+ let e = new Event(event, [namespaceName], event.name, type, extras,
+ event.unsupported || false,
+ event.permissions || null);
+ this.register(namespaceName, event.name, e);
+ },
+
+ init() {
+ if (this.initialized) {
+ return;
+ }
+ this.initialized = true;
+
+ if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ let data = Services.cpmm.initialProcessData;
+ let schemas = data["Extension:Schemas"];
+ if (schemas) {
+ this.schemaJSON = schemas;
+ }
+ Services.cpmm.addMessageListener("Schema:Add", this);
+ }
+
+ this.flushSchemas();
+ },
+
+ receiveMessage(msg) {
+ switch (msg.name) {
+ case "Schema:Add":
+ this.schemaJSON.set(msg.data.url, msg.data.schema);
+ this.flushSchemas();
+ break;
+
+ case "Schema:Delete":
+ this.schemaJSON.delete(msg.data.url);
+ this.flushSchemas();
+ break;
+ }
+ },
+
+ flushSchemas() {
+ XPCOMUtils.defineLazyGetter(this, "namespaces",
+ () => this.parseSchemas());
+ },
+
+ parseSchemas() {
+ Object.defineProperty(this, "namespaces", {
+ enumerable: true,
+ configurable: true,
+ value: new Map(),
+ });
+
+ for (let json of this.schemaJSON.values()) {
+ try {
+ this.loadSchema(json);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ }
+
+ return this.namespaces;
+ },
+
+ loadSchema(json) {
+ for (let namespace of json) {
+ let name = namespace.namespace;
+
+ let types = namespace.types || [];
+ for (let type of types) {
+ this.loadType(name, type);
+ }
+
+ let properties = namespace.properties || {};
+ for (let propertyName of Object.keys(properties)) {
+ this.loadProperty(name, propertyName, properties[propertyName]);
+ }
+
+ let functions = namespace.functions || [];
+ for (let fun of functions) {
+ this.loadFunction(name, fun);
+ }
+
+ let events = namespace.events || [];
+ for (let event of events) {
+ this.loadEvent(name, event);
+ }
+
+ let ns = this.namespaces.get(name);
+ ns.permissions = namespace.permissions || null;
+ ns.allowedContexts = namespace.allowedContexts || [];
+ ns.defaultContexts = namespace.defaultContexts || [];
+ }
+ },
+
+ load(url) {
+ if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_CONTENT) {
+ return readJSON(url).then(json => {
+ this.schemaJSON.set(url, json);
+
+ let data = Services.ppmm.initialProcessData;
+ data["Extension:Schemas"] = this.schemaJSON;
+
+ Services.ppmm.broadcastAsyncMessage("Schema:Add", {url, schema: json});
+
+ this.flushSchemas();
+ });
+ }
+ },
+
+ unload(url) {
+ this.schemaJSON.delete(url);
+
+ let data = Services.ppmm.initialProcessData;
+ data["Extension:Schemas"] = this.schemaJSON;
+
+ Services.ppmm.broadcastAsyncMessage("Schema:Delete", {url});
+
+ this.flushSchemas();
+ },
+
+ /**
+ * Checks whether a given object has the necessary permissions to
+ * expose the given namespace.
+ *
+ * @param {string} namespace
+ * The top-level namespace to check permissions for.
+ * @param {object} wrapperFuncs
+ * Wrapper functions for the given context.
+ * @param {function} wrapperFuncs.hasPermission
+ * A function which, when given a string argument, returns true
+ * if the context has the given permission.
+ * @returns {boolean}
+ * True if the context has permission for the given namespace.
+ */
+ checkPermissions(namespace, wrapperFuncs) {
+ let ns = this.namespaces.get(namespace);
+ if (ns && ns.permissions) {
+ return ns.permissions.some(perm => wrapperFuncs.hasPermission(perm));
+ }
+ return true;
+ },
+
+ exportLazyGetter,
+
+ /**
+ * Inject registered extension APIs into `dest`.
+ *
+ * @param {object} dest The root namespace for the APIs.
+ * This object is usually exposed to extensions as "chrome" or "browser".
+ * @param {object} wrapperFuncs An implementation of the InjectionContext
+ * interface, which runs the actual functionality of the generated API.
+ */
+ inject(dest, wrapperFuncs) {
+ let context = new InjectionContext(wrapperFuncs);
+
+ let createNamespace = ns => {
+ let obj = Cu.createObjectIn(dest);
+
+ for (let [name, entry] of ns) {
+ let allowedContexts = entry.allowedContexts;
+ if (!allowedContexts.length) {
+ allowedContexts = ns.defaultContexts;
+ }
+
+ if (context.shouldInject(ns.name, name, allowedContexts)) {
+ entry.inject([ns.name], name, obj, context);
+ }
+ }
+
+ // Remove the namespace object if it is empty
+ if (Object.keys(obj).length) {
+ return obj;
+ }
+ };
+
+ let createNestedNamespaces = (parent, namespaces) => {
+ for (let [prop, namespace] of namespaces) {
+ if (namespace instanceof DeepMap) {
+ exportLazyGetter(parent, prop, () => {
+ let obj = Cu.createObjectIn(parent);
+ createNestedNamespaces(obj, namespace);
+ return obj;
+ });
+ } else {
+ exportLazyGetter(parent, prop,
+ () => createNamespace(namespace));
+ }
+ }
+ };
+
+ let nestedNamespaces = new DeepMap();
+ for (let ns of this.namespaces.values()) {
+ if (ns.permissions && !ns.permissions.some(perm => context.hasPermission(perm))) {
+ continue;
+ }
+
+ if (!wrapperFuncs.shouldInject(ns.name, null, ns.allowedContexts)) {
+ continue;
+ }
+
+ if (ns.name.includes(".")) {
+ let path = ns.name.split(".");
+ let leafName = path.pop();
+
+ let parent = nestedNamespaces.getPath(...path);
+
+ parent.set(leafName, ns);
+ } else {
+ exportLazyGetter(dest, ns.name,
+ () => createNamespace(ns));
+ }
+ }
+
+ createNestedNamespaces(dest, nestedNamespaces);
+ },
+
+ /**
+ * Normalize `obj` according to the loaded schema for `typeName`.
+ *
+ * @param {object} obj The object to normalize against the schema.
+ * @param {string} typeName The name in the format namespace.propertyname
+ * @param {object} context An implementation of Context. Any validation errors
+ * are reported to the given context.
+ * @returns {object} The normalized object.
+ */
+ normalize(obj, typeName, context) {
+ let [namespaceName, prop] = typeName.split(".");
+ let ns = this.namespaces.get(namespaceName);
+ let type = ns.get(prop);
+
+ return type.normalize(obj, new Context(context));
+ },
+};
diff --git a/toolkit/components/webextensions/ext-alarms.js b/toolkit/components/webextensions/ext-alarms.js
new file mode 100644
index 000000000..2171e7dba
--- /dev/null
+++ b/toolkit/components/webextensions/ext-alarms.js
@@ -0,0 +1,155 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ EventManager,
+} = ExtensionUtils;
+
+// WeakMap[Extension -> Map[name -> Alarm]]
+var alarmsMap = new WeakMap();
+
+// WeakMap[Extension -> Set[callback]]
+var alarmCallbacksMap = new WeakMap();
+
+// Manages an alarm created by the extension (alarms API).
+function Alarm(extension, name, alarmInfo) {
+ this.extension = extension;
+ this.name = name;
+ this.when = alarmInfo.when;
+ this.delayInMinutes = alarmInfo.delayInMinutes;
+ this.periodInMinutes = alarmInfo.periodInMinutes;
+ this.canceled = false;
+
+ let delay, scheduledTime;
+ if (this.when) {
+ scheduledTime = this.when;
+ delay = this.when - Date.now();
+ } else {
+ if (!this.delayInMinutes) {
+ this.delayInMinutes = this.periodInMinutes;
+ }
+ delay = this.delayInMinutes * 60 * 1000;
+ scheduledTime = Date.now() + delay;
+ }
+
+ this.scheduledTime = scheduledTime;
+
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.init(this, delay, Ci.nsITimer.TYPE_ONE_SHOT);
+ this.timer = timer;
+}
+
+Alarm.prototype = {
+ clear() {
+ this.timer.cancel();
+ alarmsMap.get(this.extension).delete(this.name);
+ this.canceled = true;
+ },
+
+ observe(subject, topic, data) {
+ if (this.canceled) {
+ return;
+ }
+
+ for (let callback of alarmCallbacksMap.get(this.extension)) {
+ callback(this);
+ }
+
+ if (!this.periodInMinutes) {
+ this.clear();
+ return;
+ }
+
+ let delay = this.periodInMinutes * 60 * 1000;
+ this.scheduledTime = Date.now() + delay;
+ this.timer.init(this, delay, Ci.nsITimer.TYPE_ONE_SHOT);
+ },
+
+ get data() {
+ return {
+ name: this.name,
+ scheduledTime: this.scheduledTime,
+ periodInMinutes: this.periodInMinutes,
+ };
+ },
+};
+
+/* eslint-disable mozilla/balanced-listeners */
+extensions.on("startup", (type, extension) => {
+ alarmsMap.set(extension, new Map());
+ alarmCallbacksMap.set(extension, new Set());
+});
+
+extensions.on("shutdown", (type, extension) => {
+ if (alarmsMap.has(extension)) {
+ for (let alarm of alarmsMap.get(extension).values()) {
+ alarm.clear();
+ }
+ alarmsMap.delete(extension);
+ alarmCallbacksMap.delete(extension);
+ }
+});
+/* eslint-enable mozilla/balanced-listeners */
+
+extensions.registerSchemaAPI("alarms", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ alarms: {
+ create: function(name, alarmInfo) {
+ name = name || "";
+ let alarms = alarmsMap.get(extension);
+ if (alarms.has(name)) {
+ alarms.get(name).clear();
+ }
+ let alarm = new Alarm(extension, name, alarmInfo);
+ alarms.set(alarm.name, alarm);
+ },
+
+ get: function(name) {
+ name = name || "";
+ let alarms = alarmsMap.get(extension);
+ if (alarms.has(name)) {
+ return Promise.resolve(alarms.get(name).data);
+ }
+ return Promise.resolve();
+ },
+
+ getAll: function() {
+ let result = Array.from(alarmsMap.get(extension).values(), alarm => alarm.data);
+ return Promise.resolve(result);
+ },
+
+ clear: function(name) {
+ name = name || "";
+ let alarms = alarmsMap.get(extension);
+ if (alarms.has(name)) {
+ alarms.get(name).clear();
+ return Promise.resolve(true);
+ }
+ return Promise.resolve(false);
+ },
+
+ clearAll: function() {
+ let cleared = false;
+ for (let alarm of alarmsMap.get(extension).values()) {
+ alarm.clear();
+ cleared = true;
+ }
+ return Promise.resolve(cleared);
+ },
+
+ onAlarm: new EventManager(context, "alarms.onAlarm", fire => {
+ let callback = alarm => {
+ fire(alarm.data);
+ };
+
+ alarmCallbacksMap.get(extension).add(callback);
+ return () => {
+ alarmCallbacksMap.get(extension).delete(callback);
+ };
+ }).api(),
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-backgroundPage.js b/toolkit/components/webextensions/ext-backgroundPage.js
new file mode 100644
index 000000000..fce6100ca
--- /dev/null
+++ b/toolkit/components/webextensions/ext-backgroundPage.js
@@ -0,0 +1,147 @@
+"use strict";
+
+var {interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+const {
+ promiseDocumentLoaded,
+ promiseObserved,
+} = ExtensionUtils;
+
+const XUL_URL = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURI(
+ `<?xml version="1.0"?>
+ <window id="documentElement"/>`);
+
+// WeakMap[Extension -> BackgroundPage]
+var backgroundPagesMap = new WeakMap();
+
+// Responsible for the background_page section of the manifest.
+function BackgroundPage(options, extension) {
+ this.extension = extension;
+ this.page = options.page || null;
+ this.isGenerated = !!options.scripts;
+ this.windowlessBrowser = null;
+ this.webNav = null;
+}
+
+BackgroundPage.prototype = {
+ build: Task.async(function* () {
+ let windowlessBrowser = Services.appShell.createWindowlessBrowser(true);
+ this.windowlessBrowser = windowlessBrowser;
+
+ let url;
+ if (this.page) {
+ url = this.extension.baseURI.resolve(this.page);
+ } else if (this.isGenerated) {
+ url = this.extension.baseURI.resolve("_generated_background_page.html");
+ }
+
+ if (!this.extension.isExtensionURL(url)) {
+ this.extension.manifestError("Background page must be a file within the extension");
+ url = this.extension.baseURI.resolve("_blank.html");
+ }
+
+ let system = Services.scriptSecurityManager.getSystemPrincipal();
+
+ // The windowless browser is a thin wrapper around a docShell that keeps
+ // its related resources alive. It implements nsIWebNavigation and
+ // forwards its methods to the underlying docShell, but cannot act as a
+ // docShell itself. Calling `getInterface(nsIDocShell)` gives us the
+ // underlying docShell, and `QueryInterface(nsIWebNavigation)` gives us
+ // access to the webNav methods that are already available on the
+ // windowless browser, but contrary to appearances, they are not the same
+ // object.
+ let chromeShell = windowlessBrowser.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell)
+ .QueryInterface(Ci.nsIWebNavigation);
+
+ if (PrivateBrowsingUtils.permanentPrivateBrowsing) {
+ let attrs = chromeShell.getOriginAttributes();
+ attrs.privateBrowsingId = 1;
+ chromeShell.setOriginAttributes(attrs);
+ }
+
+ chromeShell.useGlobalHistory = false;
+ chromeShell.createAboutBlankContentViewer(system);
+ chromeShell.loadURI(XUL_URL, 0, null, null, null);
+
+
+ yield promiseObserved("chrome-document-global-created",
+ win => win.document == chromeShell.document);
+
+ let chromeDoc = yield promiseDocumentLoaded(chromeShell.document);
+
+ let browser = chromeDoc.createElement("browser");
+ browser.setAttribute("type", "content");
+ browser.setAttribute("disableglobalhistory", "true");
+ chromeDoc.documentElement.appendChild(browser);
+
+ extensions.emit("extension-browser-inserted", browser);
+ browser.messageManager.sendAsyncMessage("Extension:InitExtensionView", {
+ viewType: "background",
+ url,
+ });
+
+ yield new Promise(resolve => {
+ browser.messageManager.addMessageListener("Extension:ExtensionViewLoaded", function onLoad() {
+ browser.messageManager.removeMessageListener("Extension:ExtensionViewLoaded", onLoad);
+ resolve();
+ });
+ });
+
+ // TODO(robwu): This is not webext-oop compatible.
+ this.webNav = browser.docShell.QueryInterface(Ci.nsIWebNavigation);
+ let window = this.webNav.document.defaultView;
+
+
+ // Set the add-on's main debugger global, for use in the debugger
+ // console.
+ if (this.extension.addonData.instanceID) {
+ AddonManager.getAddonByInstanceID(this.extension.addonData.instanceID)
+ .then(addon => addon.setDebugGlobal(window));
+ }
+
+ this.extension.emit("startup");
+ }),
+
+ shutdown() {
+ if (this.extension.addonData.instanceID) {
+ AddonManager.getAddonByInstanceID(this.extension.addonData.instanceID)
+ .then(addon => addon.setDebugGlobal(null));
+ }
+
+ // Navigate away from the background page to invalidate any
+ // setTimeouts or other callbacks.
+ if (this.webNav) {
+ this.webNav.loadURI("about:blank", 0, null, null, null);
+ this.webNav = null;
+ }
+
+ this.windowlessBrowser.loadURI("about:blank", 0, null, null, null);
+ this.windowlessBrowser.close();
+ this.windowlessBrowser = null;
+ },
+};
+
+/* eslint-disable mozilla/balanced-listeners */
+extensions.on("manifest_background", (type, directive, extension, manifest) => {
+ let bgPage = new BackgroundPage(manifest.background, extension);
+ backgroundPagesMap.set(extension, bgPage);
+ return bgPage.build();
+});
+
+extensions.on("shutdown", (type, extension) => {
+ if (backgroundPagesMap.has(extension)) {
+ backgroundPagesMap.get(extension).shutdown();
+ backgroundPagesMap.delete(extension);
+ }
+});
+/* eslint-enable mozilla/balanced-listeners */
diff --git a/toolkit/components/webextensions/ext-browser-content.js b/toolkit/components/webextensions/ext-browser-content.js
new file mode 100644
index 000000000..e14ca50d6
--- /dev/null
+++ b/toolkit/components/webextensions/ext-browser-content.js
@@ -0,0 +1,217 @@
+/* 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";
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout",
+ "resource://gre/modules/Timer.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "require",
+ "resource://devtools/shared/Loader.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
+ "resource://gre/modules/Timer.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "colorUtils", () => {
+ return require("devtools/shared/css/color").colorUtils;
+});
+
+const {
+ stylesheetMap,
+} = ExtensionUtils;
+
+/* globals addMessageListener, content, docShell, sendAsyncMessage */
+
+// Minimum time between two resizes.
+const RESIZE_TIMEOUT = 100;
+
+const BrowserListener = {
+ init({allowScriptsToClose, fixedWidth, maxHeight, maxWidth, stylesheets}) {
+ this.fixedWidth = fixedWidth;
+ this.stylesheets = stylesheets || [];
+
+ this.maxWidth = maxWidth;
+ this.maxHeight = maxHeight;
+
+ this.oldBackground = null;
+
+ if (allowScriptsToClose) {
+ content.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils)
+ .allowScriptsToClose();
+ }
+
+ addEventListener("DOMWindowCreated", this, true);
+ addEventListener("load", this, true);
+ addEventListener("DOMContentLoaded", this, true);
+ addEventListener("DOMWindowClose", this, true);
+ addEventListener("MozScrolledAreaChanged", this, true);
+ },
+
+ destroy() {
+ removeEventListener("DOMWindowCreated", this, true);
+ removeEventListener("load", this, true);
+ removeEventListener("DOMContentLoaded", this, true);
+ removeEventListener("DOMWindowClose", this, true);
+ removeEventListener("MozScrolledAreaChanged", this, true);
+ },
+
+ receiveMessage({name, data}) {
+ if (name === "Extension:InitBrowser") {
+ this.init(data);
+ }
+ },
+
+ handleEvent(event) {
+ switch (event.type) {
+ case "DOMWindowCreated":
+ if (event.target === content.document) {
+ let winUtils = content.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindowUtils);
+
+ for (let url of this.stylesheets) {
+ winUtils.addSheet(stylesheetMap.get(url), winUtils.AGENT_SHEET);
+ }
+ }
+ break;
+
+ case "DOMWindowClose":
+ if (event.target === content) {
+ event.preventDefault();
+
+ sendAsyncMessage("Extension:DOMWindowClose");
+ }
+ break;
+
+ case "DOMContentLoaded":
+ if (event.target === content.document) {
+ sendAsyncMessage("Extension:BrowserContentLoaded", {url: content.location.href});
+ this.handleDOMChange(true);
+ }
+ break;
+
+ case "load":
+ if (event.target.contentWindow === content) {
+ // For about:addons inline <browsers>, we currently receive a load
+ // event on the <browser> element, but no load or DOMContentLoaded
+ // events from the content window.
+ sendAsyncMessage("Extension:BrowserContentLoaded", {url: content.location.href});
+ } else if (event.target !== content.document) {
+ break;
+ }
+
+ // We use a capturing listener, so we get this event earlier than any
+ // load listeners in the content page. Resizing after a timeout ensures
+ // that we calculate the size after the entire event cycle has completed
+ // (unless someone spins the event loop, anyway), and hopefully after
+ // the content has made any modifications.
+ Promise.resolve().then(() => {
+ this.handleDOMChange(true);
+ });
+
+ // Mutation observer to make sure the panel shrinks when the content does.
+ new content.MutationObserver(this.handleDOMChange.bind(this)).observe(
+ content.document.documentElement, {
+ attributes: true,
+ characterData: true,
+ childList: true,
+ subtree: true,
+ });
+ break;
+
+ case "MozScrolledAreaChanged":
+ this.handleDOMChange();
+ break;
+ }
+ },
+
+ // Resizes the browser to match the preferred size of the content (debounced).
+ handleDOMChange(ignoreThrottling = false) {
+ if (ignoreThrottling && this.resizeTimeout) {
+ clearTimeout(this.resizeTimeout);
+ this.resizeTimeout = null;
+ }
+
+ if (this.resizeTimeout == null) {
+ this.resizeTimeout = setTimeout(() => {
+ try {
+ if (content) {
+ this._handleDOMChange("delayed");
+ }
+ } finally {
+ this.resizeTimeout = null;
+ }
+ }, RESIZE_TIMEOUT);
+
+ this._handleDOMChange();
+ }
+ },
+
+ _handleDOMChange(detail) {
+ let doc = content.document;
+
+ let body = doc.body;
+ if (!body || doc.compatMode === "BackCompat") {
+ // In quirks mode, the root element is used as the scroll frame, and the
+ // body lies about its scroll geometry, and returns the values for the
+ // root instead.
+ body = doc.documentElement;
+ }
+
+
+ let result;
+ if (this.fixedWidth) {
+ // If we're in a fixed-width area (namely a slide-in subview of the main
+ // menu panel), we need to calculate the view height based on the
+ // preferred height of the content document's root scrollable element at the
+ // current width, rather than the complete preferred dimensions of the
+ // content window.
+
+ // Compensate for any offsets (margin, padding, ...) between the scroll
+ // area of the body and the outer height of the document.
+ let getHeight = elem => elem.getBoundingClientRect(elem).height;
+ let bodyPadding = getHeight(doc.documentElement) - getHeight(body);
+
+ let height = Math.ceil(body.scrollHeight + bodyPadding);
+
+ result = {height, detail};
+ } else {
+ let background = doc.defaultView.getComputedStyle(body).backgroundColor;
+ let bgColor = colorUtils.colorToRGBA(background);
+ if (bgColor.a !== 1) {
+ // Ignore non-opaque backgrounds.
+ background = null;
+ }
+
+ if (background !== this.oldBackground) {
+ sendAsyncMessage("Extension:BrowserBackgroundChanged", {background});
+ }
+ this.oldBackground = background;
+
+
+ // Adjust the size of the browser based on its content's preferred size.
+ let {contentViewer} = docShell;
+ let ratio = content.devicePixelRatio;
+
+ let w = {}, h = {};
+ contentViewer.getContentSizeConstrained(this.maxWidth * ratio,
+ this.maxHeight * ratio,
+ w, h);
+
+ let width = Math.ceil(w.value / ratio);
+ let height = Math.ceil(h.value / ratio);
+
+ result = {width, height, detail};
+ }
+
+ sendAsyncMessage("Extension:BrowserResized", result);
+ },
+};
+
+addMessageListener("Extension:InitBrowser", BrowserListener);
diff --git a/toolkit/components/webextensions/ext-c-backgroundPage.js b/toolkit/components/webextensions/ext-c-backgroundPage.js
new file mode 100644
index 000000000..b5074dd9a
--- /dev/null
+++ b/toolkit/components/webextensions/ext-c-backgroundPage.js
@@ -0,0 +1,45 @@
+"use strict";
+
+global.initializeBackgroundPage = (contentWindow) => {
+ // Override the `alert()` method inside background windows;
+ // we alias it to console.log().
+ // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1203394
+ let alertDisplayedWarning = false;
+ let alertOverwrite = text => {
+ if (!alertDisplayedWarning) {
+ require("devtools/client/framework/devtools-browser");
+
+ let hudservice = require("devtools/client/webconsole/hudservice");
+ hudservice.openBrowserConsoleOrFocus();
+
+ contentWindow.console.warn("alert() is not supported in background windows; please use console.log instead.");
+
+ alertDisplayedWarning = true;
+ }
+
+ contentWindow.console.log(text);
+ };
+ Cu.exportFunction(alertOverwrite, contentWindow, {defineAs: "alert"});
+};
+
+extensions.registerSchemaAPI("extension", "addon_child", context => {
+ function getBackgroundPage() {
+ for (let view of context.extension.views) {
+ if (view.viewType == "background" && context.principal.subsumes(view.principal)) {
+ return view.contentWindow;
+ }
+ }
+ return null;
+ }
+ return {
+ extension: {
+ getBackgroundPage,
+ },
+
+ runtime: {
+ getBackgroundPage() {
+ return context.cloneScope.Promise.resolve(getBackgroundPage());
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-c-extension.js b/toolkit/components/webextensions/ext-c-extension.js
new file mode 100644
index 000000000..669309bea
--- /dev/null
+++ b/toolkit/components/webextensions/ext-c-extension.js
@@ -0,0 +1,57 @@
+"use strict";
+
+XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm");
+
+function extensionApiFactory(context) {
+ return {
+ extension: {
+ getURL(url) {
+ return context.extension.baseURI.resolve(url);
+ },
+
+ get lastError() {
+ return context.lastError;
+ },
+
+ get inIncognitoContext() {
+ return context.incognito;
+ },
+ },
+ };
+}
+
+extensions.registerSchemaAPI("extension", "addon_child", extensionApiFactory);
+extensions.registerSchemaAPI("extension", "content_child", extensionApiFactory);
+extensions.registerSchemaAPI("extension", "addon_child", context => {
+ return {
+ extension: {
+ getViews: function(fetchProperties) {
+ let result = Cu.cloneInto([], context.cloneScope);
+
+ for (let view of context.extension.views) {
+ if (!view.active) {
+ continue;
+ }
+ if (!context.principal.subsumes(view.principal)) {
+ continue;
+ }
+
+ if (fetchProperties !== null) {
+ if (fetchProperties.type !== null && view.viewType != fetchProperties.type) {
+ continue;
+ }
+
+ if (fetchProperties.windowId !== null && view.windowId != fetchProperties.windowId) {
+ continue;
+ }
+ }
+
+ result.push(view.contentWindow);
+ }
+
+ return result;
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-c-runtime.js b/toolkit/components/webextensions/ext-c-runtime.js
new file mode 100644
index 000000000..8adca60ca
--- /dev/null
+++ b/toolkit/components/webextensions/ext-c-runtime.js
@@ -0,0 +1,93 @@
+"use strict";
+
+function runtimeApiFactory(context) {
+ let {extension} = context;
+
+ return {
+ runtime: {
+ onConnect: context.messenger.onConnect("runtime.onConnect"),
+
+ onMessage: context.messenger.onMessage("runtime.onMessage"),
+
+ connect: function(extensionId, connectInfo) {
+ let name = connectInfo !== null && connectInfo.name || "";
+ extensionId = extensionId || extension.id;
+ let recipient = {extensionId};
+
+ return context.messenger.connect(context.messageManager, name, recipient);
+ },
+
+ sendMessage: function(...args) {
+ let options; // eslint-disable-line no-unused-vars
+ let extensionId, message, responseCallback;
+ if (typeof args[args.length - 1] == "function") {
+ responseCallback = args.pop();
+ }
+ if (!args.length) {
+ return Promise.reject({message: "runtime.sendMessage's message argument is missing"});
+ } else if (args.length == 1) {
+ message = args[0];
+ } else if (args.length == 2) {
+ if (typeof args[0] == "string" && args[0]) {
+ [extensionId, message] = args;
+ } else {
+ [message, options] = args;
+ }
+ } else if (args.length == 3) {
+ [extensionId, message, options] = args;
+ } else if (args.length == 4 && !responseCallback) {
+ return Promise.reject({message: "runtime.sendMessage's last argument is not a function"});
+ } else {
+ return Promise.reject({message: "runtime.sendMessage received too many arguments"});
+ }
+
+ if (extensionId != null && typeof extensionId != "string") {
+ return Promise.reject({message: "runtime.sendMessage's extensionId argument is invalid"});
+ }
+ if (options != null && typeof options != "object") {
+ return Promise.reject({message: "runtime.sendMessage's options argument is invalid"});
+ }
+ // TODO(robwu): Validate option keys and values when we support it.
+
+ extensionId = extensionId || extension.id;
+ let recipient = {extensionId};
+
+ return context.messenger.sendMessage(context.messageManager, message, recipient, responseCallback);
+ },
+
+ connectNative(application) {
+ let recipient = {
+ childId: context.childManager.id,
+ toNativeApp: application,
+ };
+
+ return context.messenger.connectNative(context.messageManager, "", recipient);
+ },
+
+ sendNativeMessage(application, message) {
+ let recipient = {
+ childId: context.childManager.id,
+ toNativeApp: application,
+ };
+ return context.messenger.sendNativeMessage(context.messageManager, message, recipient);
+ },
+
+ get lastError() {
+ return context.lastError;
+ },
+
+ getManifest() {
+ return Cu.cloneInto(extension.manifest, context.cloneScope);
+ },
+
+ id: extension.id,
+
+ getURL: function(url) {
+ return extension.baseURI.resolve(url);
+ },
+ },
+ };
+}
+
+extensions.registerSchemaAPI("runtime", "addon_child", runtimeApiFactory);
+extensions.registerSchemaAPI("runtime", "content_child", runtimeApiFactory);
diff --git a/toolkit/components/webextensions/ext-c-storage.js b/toolkit/components/webextensions/ext-c-storage.js
new file mode 100644
index 000000000..e8d53058f
--- /dev/null
+++ b/toolkit/components/webextensions/ext-c-storage.js
@@ -0,0 +1,62 @@
+"use strict";
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage",
+ "resource://gre/modules/ExtensionStorage.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+function storageApiFactory(context) {
+ function sanitize(items) {
+ // The schema validator already takes care of arrays (which are only allowed
+ // to contain strings). Strings and null are safe values.
+ if (typeof items != "object" || items === null || Array.isArray(items)) {
+ return items;
+ }
+ // If we got here, then `items` is an object generated by `ObjectType`'s
+ // `normalize` method from Schemas.jsm. The object returned by `normalize`
+ // lives in this compartment, while the values live in compartment of
+ // `context.contentWindow`. The `sanitize` method runs with the principal
+ // of `context`, so we cannot just use `ExtensionStorage.sanitize` because
+ // it is not allowed to access properties of `items`.
+ // So we enumerate all properties and sanitize each value individually.
+ let sanitized = {};
+ for (let [key, value] of Object.entries(items)) {
+ sanitized[key] = ExtensionStorage.sanitize(value, context);
+ }
+ return sanitized;
+ }
+ return {
+ storage: {
+ local: {
+ get: function(keys) {
+ keys = sanitize(keys);
+ return context.childManager.callParentAsyncFunction("storage.local.get", [
+ keys,
+ ]);
+ },
+ set: function(items) {
+ items = sanitize(items);
+ return context.childManager.callParentAsyncFunction("storage.local.set", [
+ items,
+ ]);
+ },
+ },
+
+ sync: {
+ get: function(keys) {
+ keys = sanitize(keys);
+ return context.childManager.callParentAsyncFunction("storage.sync.get", [
+ keys,
+ ]);
+ },
+ set: function(items) {
+ items = sanitize(items);
+ return context.childManager.callParentAsyncFunction("storage.sync.set", [
+ items,
+ ]);
+ },
+ },
+ },
+ };
+}
+extensions.registerSchemaAPI("storage", "addon_child", storageApiFactory);
+extensions.registerSchemaAPI("storage", "content_child", storageApiFactory);
diff --git a/toolkit/components/webextensions/ext-c-test.js b/toolkit/components/webextensions/ext-c-test.js
new file mode 100644
index 000000000..b0c92f79f
--- /dev/null
+++ b/toolkit/components/webextensions/ext-c-test.js
@@ -0,0 +1,188 @@
+"use strict";
+
+Components.utils.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ SingletonEventManager,
+} = ExtensionUtils;
+
+/**
+ * Checks whether the given error matches the given expectations.
+ *
+ * @param {*} error
+ * The error to check.
+ * @param {string|RegExp|function|null} expectedError
+ * The expectation to check against. If this parameter is:
+ *
+ * - a string, the error message must exactly equal the string.
+ * - a regular expression, it must match the error message.
+ * - a function, it is called with the error object and its
+ * return value is returned.
+ * - null, the function always returns true.
+ * @param {BaseContext} context
+ *
+ * @returns {boolean}
+ * True if the error matches the expected error.
+ */
+function errorMatches(error, expectedError, context) {
+ if (expectedError === null) {
+ return true;
+ }
+
+ if (typeof expectedError === "function") {
+ return context.runSafeWithoutClone(expectedError, error);
+ }
+
+ if (typeof error !== "object" || error == null ||
+ typeof error.message !== "string") {
+ return false;
+ }
+
+ if (typeof expectedError === "string") {
+ return error.message === expectedError;
+ }
+
+ try {
+ return expectedError.test(error.message);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+
+ return false;
+}
+
+/**
+ * Calls .toSource() on the given value, but handles null, undefined,
+ * and errors.
+ *
+ * @param {*} value
+ * @returns {string}
+ */
+function toSource(value) {
+ if (value === null) {
+ return "null";
+ }
+ if (value === undefined) {
+ return "undefined";
+ }
+ if (typeof value === "string") {
+ return JSON.stringify(value);
+ }
+
+ try {
+ return String(value.toSource());
+ } catch (e) {
+ return "<unknown>";
+ }
+}
+
+function makeTestAPI(context) {
+ const {extension} = context;
+
+ function getStack() {
+ return new context.cloneScope.Error().stack.replace(/^/gm, " ");
+ }
+
+ function assertTrue(value, msg) {
+ extension.emit("test-result", Boolean(value), String(msg), getStack());
+ }
+
+ return {
+ test: {
+ sendMessage(...args) {
+ extension.emit("test-message", ...args);
+ },
+
+ notifyPass(msg) {
+ extension.emit("test-done", true, msg, getStack());
+ },
+
+ notifyFail(msg) {
+ extension.emit("test-done", false, msg, getStack());
+ },
+
+ log(msg) {
+ extension.emit("test-log", true, msg, getStack());
+ },
+
+ fail(msg) {
+ assertTrue(false, msg);
+ },
+
+ succeed(msg) {
+ assertTrue(true, msg);
+ },
+
+ assertTrue(value, msg) {
+ assertTrue(value, msg);
+ },
+
+ assertFalse(value, msg) {
+ assertTrue(!value, msg);
+ },
+
+ assertEq(expected, actual, msg) {
+ let equal = expected === actual;
+
+ expected = String(expected);
+ actual = String(actual);
+
+ if (!equal && expected === actual) {
+ actual += " (different)";
+ }
+ extension.emit("test-eq", equal, String(msg), expected, actual, getStack());
+ },
+
+ assertRejects(promise, expectedError, msg) {
+ // Wrap in a native promise for consistency.
+ promise = Promise.resolve(promise);
+
+ if (msg) {
+ msg = `: ${msg}`;
+ }
+
+ return promise.then(result => {
+ assertTrue(false, `Promise resolved, expected rejection${msg}`);
+ }, error => {
+ let errorMessage = toSource(error && error.message);
+
+ assertTrue(errorMatches(error, expectedError, context),
+ `Promise rejected, expecting rejection to match ${toSource(expectedError)}, ` +
+ `got ${errorMessage}${msg}`);
+ });
+ },
+
+ assertThrows(func, expectedError, msg) {
+ if (msg) {
+ msg = `: ${msg}`;
+ }
+
+ try {
+ func();
+
+ assertTrue(false, `Function did not throw, expected error${msg}`);
+ } catch (error) {
+ let errorMessage = toSource(error && error.message);
+
+ assertTrue(errorMatches(error, expectedError, context),
+ `Function threw, expecting error to match ${toSource(expectedError)}` +
+ `got ${errorMessage}${msg}`);
+ }
+ },
+
+ onMessage: new SingletonEventManager(context, "test.onMessage", fire => {
+ let handler = (event, ...args) => {
+ context.runSafe(fire, ...args);
+ };
+
+ extension.on("test-harness-message", handler);
+ return () => {
+ extension.off("test-harness-message", handler);
+ };
+ }).api(),
+ },
+ };
+}
+
+extensions.registerSchemaAPI("test", "addon_child", makeTestAPI);
+extensions.registerSchemaAPI("test", "content_child", makeTestAPI);
+
diff --git a/toolkit/components/webextensions/ext-cookies.js b/toolkit/components/webextensions/ext-cookies.js
new file mode 100644
index 000000000..d0a703421
--- /dev/null
+++ b/toolkit/components/webextensions/ext-cookies.js
@@ -0,0 +1,484 @@
+"use strict";
+
+const {interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ContextualIdentityService",
+ "resource://gre/modules/ContextualIdentityService.jsm");
+
+var {
+ EventManager,
+} = ExtensionUtils;
+
+var DEFAULT_STORE = "firefox-default";
+var PRIVATE_STORE = "firefox-private";
+var CONTAINER_STORE = "firefox-container-";
+
+global.getCookieStoreIdForTab = function(data, tab) {
+ if (data.incognito) {
+ return PRIVATE_STORE;
+ }
+
+ if (tab.userContextId) {
+ return CONTAINER_STORE + tab.userContextId;
+ }
+
+ return DEFAULT_STORE;
+};
+
+global.isPrivateCookieStoreId = function(storeId) {
+ return storeId == PRIVATE_STORE;
+};
+
+global.isDefaultCookieStoreId = function(storeId) {
+ return storeId == DEFAULT_STORE;
+};
+
+global.isContainerCookieStoreId = function(storeId) {
+ return storeId !== null && storeId.startsWith(CONTAINER_STORE);
+};
+
+global.getContainerForCookieStoreId = function(storeId) {
+ if (!global.isContainerCookieStoreId(storeId)) {
+ return null;
+ }
+
+ let containerId = storeId.substring(CONTAINER_STORE.length);
+ if (ContextualIdentityService.getIdentityFromId(containerId)) {
+ return parseInt(containerId, 10);
+ }
+
+ return null;
+};
+
+global.isValidCookieStoreId = function(storeId) {
+ return global.isDefaultCookieStoreId(storeId) ||
+ global.isPrivateCookieStoreId(storeId) ||
+ global.isContainerCookieStoreId(storeId);
+};
+
+function convert({cookie, isPrivate}) {
+ let result = {
+ name: cookie.name,
+ value: cookie.value,
+ domain: cookie.host,
+ hostOnly: !cookie.isDomain,
+ path: cookie.path,
+ secure: cookie.isSecure,
+ httpOnly: cookie.isHttpOnly,
+ session: cookie.isSession,
+ };
+
+ if (!cookie.isSession) {
+ result.expirationDate = cookie.expiry;
+ }
+
+ if (cookie.originAttributes.userContextId) {
+ result.storeId = CONTAINER_STORE + cookie.originAttributes.userContextId;
+ } else if (cookie.originAttributes.privateBrowsingId || isPrivate) {
+ result.storeId = PRIVATE_STORE;
+ } else {
+ result.storeId = DEFAULT_STORE;
+ }
+
+ return result;
+}
+
+function isSubdomain(otherDomain, baseDomain) {
+ return otherDomain == baseDomain || otherDomain.endsWith("." + baseDomain);
+}
+
+// Checks that the given extension has permission to set the given cookie for
+// the given URI.
+function checkSetCookiePermissions(extension, uri, cookie) {
+ // Permission checks:
+ //
+ // - If the extension does not have permissions for the specified
+ // URL, it cannot set cookies for it.
+ //
+ // - If the specified URL could not set the given cookie, neither can
+ // the extension.
+ //
+ // Ideally, we would just have the cookie service make the latter
+ // determination, but that turns out to be quite complicated. At the
+ // moment, it requires constructing a cookie string and creating a
+ // dummy channel, both of which can be problematic. It also triggers
+ // a whole set of additional permission and preference checks, which
+ // may or may not be desirable.
+ //
+ // So instead, we do a similar set of checks here. Exactly what
+ // cookies a given URL should be able to set is not well-documented,
+ // and is not standardized in any standard that anyone actually
+ // follows. So instead, we follow the rules used by the cookie
+ // service.
+ //
+ // See source/netwerk/cookie/nsCookieService.cpp, in particular
+ // CheckDomain() and SetCookieInternal().
+
+ if (uri.scheme != "http" && uri.scheme != "https") {
+ return false;
+ }
+
+ if (!extension.whiteListedHosts.matchesIgnoringPath(uri)) {
+ return false;
+ }
+
+ if (!cookie.host) {
+ // If no explicit host is specified, this becomes a host-only cookie.
+ cookie.host = uri.host;
+ return true;
+ }
+
+ // A leading "." is not expected, but is tolerated if it's not the only
+ // character in the host. If there is one, start by stripping it off. We'll
+ // add a new one on success.
+ if (cookie.host.length > 1) {
+ cookie.host = cookie.host.replace(/^\./, "");
+ }
+ cookie.host = cookie.host.toLowerCase();
+
+ if (cookie.host != uri.host) {
+ // Not an exact match, so check for a valid subdomain.
+ let baseDomain;
+ try {
+ baseDomain = Services.eTLD.getBaseDomain(uri);
+ } catch (e) {
+ if (e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS ||
+ e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) {
+ // The cookie service uses these to determine whether the domain
+ // requires an exact match. We already know we don't have an exact
+ // match, so return false. In all other cases, re-raise the error.
+ return false;
+ }
+ throw e;
+ }
+
+ // The cookie domain must be a subdomain of the base domain. This prevents
+ // us from setting cookies for domains like ".co.uk".
+ // The domain of the requesting URL must likewise be a subdomain of the
+ // cookie domain. This prevents us from setting cookies for entirely
+ // unrelated domains.
+ if (!isSubdomain(cookie.host, baseDomain) ||
+ !isSubdomain(uri.host, cookie.host)) {
+ return false;
+ }
+
+ // RFC2109 suggests that we may only add cookies for sub-domains 1-level
+ // below us, but enforcing that would break the web, so we don't.
+ }
+
+ // An explicit domain was passed, so add a leading "." to make this a
+ // domain cookie.
+ cookie.host = "." + cookie.host;
+
+ // We don't do any significant checking of path permissions. RFC2109
+ // suggests we only allow sites to add cookies for sub-paths, similar to
+ // same origin policy enforcement, but no-one implements this.
+
+ return true;
+}
+
+function* query(detailsIn, props, context) {
+ // Different callers want to filter on different properties. |props|
+ // tells us which ones they're interested in.
+ let details = {};
+ props.forEach(property => {
+ if (detailsIn[property] !== null) {
+ details[property] = detailsIn[property];
+ }
+ });
+
+ if ("domain" in details) {
+ details.domain = details.domain.toLowerCase().replace(/^\./, "");
+ }
+
+ let userContextId = 0;
+ let isPrivate = context.incognito;
+ if (details.storeId) {
+ if (!global.isValidCookieStoreId(details.storeId)) {
+ return;
+ }
+
+ if (global.isDefaultCookieStoreId(details.storeId)) {
+ isPrivate = false;
+ } else if (global.isPrivateCookieStoreId(details.storeId)) {
+ isPrivate = true;
+ } else if (global.isContainerCookieStoreId(details.storeId)) {
+ isPrivate = false;
+ userContextId = global.getContainerForCookieStoreId(details.storeId);
+ if (!userContextId) {
+ return;
+ }
+ }
+ }
+
+ let storeId = DEFAULT_STORE;
+ if (isPrivate) {
+ storeId = PRIVATE_STORE;
+ } else if ("storeId" in details) {
+ storeId = details.storeId;
+ }
+
+ // We can use getCookiesFromHost for faster searching.
+ let enumerator;
+ let uri;
+ if ("url" in details) {
+ try {
+ uri = NetUtil.newURI(details.url).QueryInterface(Ci.nsIURL);
+ Services.cookies.usePrivateMode(isPrivate, () => {
+ enumerator = Services.cookies.getCookiesFromHost(uri.host, {userContextId});
+ });
+ } catch (ex) {
+ // This often happens for about: URLs
+ return;
+ }
+ } else if ("domain" in details) {
+ Services.cookies.usePrivateMode(isPrivate, () => {
+ enumerator = Services.cookies.getCookiesFromHost(details.domain, {userContextId});
+ });
+ } else {
+ Services.cookies.usePrivateMode(isPrivate, () => {
+ enumerator = Services.cookies.enumerator;
+ });
+ }
+
+ // Based on nsCookieService::GetCookieStringInternal
+ function matches(cookie) {
+ function domainMatches(host) {
+ return cookie.rawHost == host || (cookie.isDomain && host.endsWith(cookie.host));
+ }
+
+ function pathMatches(path) {
+ let cookiePath = cookie.path.replace(/\/$/, "");
+
+ if (!path.startsWith(cookiePath)) {
+ return false;
+ }
+
+ // path == cookiePath, but without the redundant string compare.
+ if (path.length == cookiePath.length) {
+ return true;
+ }
+
+ // URL path is a substring of the cookie path, so it matches if, and
+ // only if, the next character is a path delimiter.
+ let pathDelimiters = ["/", "?", "#", ";"];
+ return pathDelimiters.includes(path[cookiePath.length]);
+ }
+
+ // "Restricts the retrieved cookies to those that would match the given URL."
+ if (uri) {
+ if (!domainMatches(uri.host)) {
+ return false;
+ }
+
+ if (cookie.isSecure && uri.scheme != "https") {
+ return false;
+ }
+
+ if (!pathMatches(uri.path)) {
+ return false;
+ }
+ }
+
+ if ("name" in details && details.name != cookie.name) {
+ return false;
+ }
+
+ if (userContextId != cookie.originAttributes.userContextId) {
+ return false;
+ }
+
+ // "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."
+ if ("domain" in details && !isSubdomain(cookie.rawHost, details.domain)) {
+ return false;
+ }
+
+ // "Restricts the retrieved cookies to those whose path exactly matches this string.""
+ if ("path" in details && details.path != cookie.path) {
+ return false;
+ }
+
+ if ("secure" in details && details.secure != cookie.isSecure) {
+ return false;
+ }
+
+ if ("session" in details && details.session != cookie.isSession) {
+ return false;
+ }
+
+ // Check that the extension has permissions for this host.
+ if (!context.extension.whiteListedHosts.matchesCookie(cookie)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ while (enumerator.hasMoreElements()) {
+ let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie2);
+ if (matches(cookie)) {
+ yield {cookie, isPrivate, storeId};
+ }
+ }
+}
+
+extensions.registerSchemaAPI("cookies", "addon_parent", context => {
+ let {extension} = context;
+ let self = {
+ cookies: {
+ get: function(details) {
+ // FIXME: We don't sort by length of path and creation time.
+ for (let cookie of query(details, ["url", "name", "storeId"], context)) {
+ return Promise.resolve(convert(cookie));
+ }
+
+ // Found no match.
+ return Promise.resolve(null);
+ },
+
+ getAll: function(details) {
+ let allowed = ["url", "name", "domain", "path", "secure", "session", "storeId"];
+ let result = Array.from(query(details, allowed, context), convert);
+
+ return Promise.resolve(result);
+ },
+
+ set: function(details) {
+ let uri = NetUtil.newURI(details.url).QueryInterface(Ci.nsIURL);
+
+ let path;
+ if (details.path !== null) {
+ path = details.path;
+ } else {
+ // This interface essentially emulates the behavior of the
+ // Set-Cookie header. In the case of an omitted path, the cookie
+ // service uses the directory path of the requesting URL, ignoring
+ // any filename or query parameters.
+ path = uri.directory;
+ }
+
+ let name = details.name !== null ? details.name : "";
+ let value = details.value !== null ? details.value : "";
+ let secure = details.secure !== null ? details.secure : false;
+ let httpOnly = details.httpOnly !== null ? details.httpOnly : false;
+ let isSession = details.expirationDate === null;
+ let expiry = isSession ? Number.MAX_SAFE_INTEGER : details.expirationDate;
+ let isPrivate = context.incognito;
+ let userContextId = 0;
+ if (global.isDefaultCookieStoreId(details.storeId)) {
+ isPrivate = false;
+ } else if (global.isPrivateCookieStoreId(details.storeId)) {
+ isPrivate = true;
+ } else if (global.isContainerCookieStoreId(details.storeId)) {
+ let containerId = global.getContainerForCookieStoreId(details.storeId);
+ if (containerId === null) {
+ return Promise.reject({message: `Illegal storeId: ${details.storeId}`});
+ }
+ isPrivate = false;
+ userContextId = containerId;
+ } else if (details.storeId !== null) {
+ return Promise.reject({message: "Unknown storeId"});
+ }
+
+ let cookieAttrs = {host: details.domain, path: path, isSecure: secure};
+ if (!checkSetCookiePermissions(extension, uri, cookieAttrs)) {
+ return Promise.reject({message: `Permission denied to set cookie ${JSON.stringify(details)}`});
+ }
+
+ // The permission check may have modified the domain, so use
+ // the new value instead.
+ Services.cookies.usePrivateMode(isPrivate, () => {
+ Services.cookies.add(cookieAttrs.host, path, name, value,
+ secure, httpOnly, isSession, expiry, {userContextId});
+ });
+
+ return self.cookies.get(details);
+ },
+
+ remove: function(details) {
+ for (let {cookie, isPrivate, storeId} of query(details, ["url", "name", "storeId"], context)) {
+ Services.cookies.usePrivateMode(isPrivate, () => {
+ Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes);
+ });
+
+ // Todo: could there be multiple per subdomain?
+ return Promise.resolve({
+ url: details.url,
+ name: details.name,
+ storeId,
+ });
+ }
+
+ return Promise.resolve(null);
+ },
+
+ getAllCookieStores: function() {
+ let data = {};
+ for (let window of WindowListManager.browserWindows()) {
+ let tabs = TabManager.for(extension).getTabs(window);
+ for (let tab of tabs) {
+ if (!(tab.cookieStoreId in data)) {
+ data[tab.cookieStoreId] = [];
+ }
+ data[tab.cookieStoreId].push(tab);
+ }
+ }
+
+ let result = [];
+ for (let key in data) {
+ result.push({id: key, tabIds: data[key], incognito: key == PRIVATE_STORE});
+ }
+ return Promise.resolve(result);
+ },
+
+ onChanged: new EventManager(context, "cookies.onChanged", fire => {
+ let observer = (subject, topic, data) => {
+ let notify = (removed, cookie, cause) => {
+ cookie.QueryInterface(Ci.nsICookie2);
+
+ if (extension.whiteListedHosts.matchesCookie(cookie)) {
+ fire({removed, cookie: convert({cookie, isPrivate: topic == "private-cookie-changed"}), cause});
+ }
+ };
+
+ // We do our best effort here to map the incompatible states.
+ switch (data) {
+ case "deleted":
+ notify(true, subject, "explicit");
+ break;
+ case "added":
+ notify(false, subject, "explicit");
+ break;
+ case "changed":
+ notify(true, subject, "overwrite");
+ notify(false, subject, "explicit");
+ break;
+ case "batch-deleted":
+ subject.QueryInterface(Ci.nsIArray);
+ for (let i = 0; i < subject.length; i++) {
+ let cookie = subject.queryElementAt(i, Ci.nsICookie2);
+ if (!cookie.isSession && cookie.expiry * 1000 <= Date.now()) {
+ notify(true, cookie, "expired");
+ } else {
+ notify(true, cookie, "evicted");
+ }
+ }
+ break;
+ }
+ };
+
+ Services.obs.addObserver(observer, "cookie-changed", false);
+ Services.obs.addObserver(observer, "private-cookie-changed", false);
+ return () => {
+ Services.obs.removeObserver(observer, "cookie-changed");
+ Services.obs.removeObserver(observer, "private-cookie-changed");
+ };
+ }).api(),
+ },
+ };
+
+ return self;
+});
diff --git a/toolkit/components/webextensions/ext-downloads.js b/toolkit/components/webextensions/ext-downloads.js
new file mode 100644
index 000000000..132814ae4
--- /dev/null
+++ b/toolkit/components/webextensions/ext-downloads.js
@@ -0,0 +1,799 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "Downloads",
+ "resource://gre/modules/Downloads.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths",
+ "resource://gre/modules/DownloadPaths.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
+ "resource://gre/modules/FileUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter",
+ "resource://devtools/shared/event-emitter.js");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+const {
+ ignoreEvent,
+ normalizeTime,
+ runSafeSync,
+ SingletonEventManager,
+ PlatformInfo,
+} = ExtensionUtils;
+
+const DOWNLOAD_ITEM_FIELDS = ["id", "url", "referrer", "filename", "incognito",
+ "danger", "mime", "startTime", "endTime",
+ "estimatedEndTime", "state",
+ "paused", "canResume", "error",
+ "bytesReceived", "totalBytes",
+ "fileSize", "exists",
+ "byExtensionId", "byExtensionName"];
+
+// Fields that we generate onChanged events for.
+const DOWNLOAD_ITEM_CHANGE_FIELDS = ["endTime", "state", "paused", "canResume",
+ "error", "exists"];
+
+// From https://fetch.spec.whatwg.org/#forbidden-header-name
+const FORBIDDEN_HEADERS = ["ACCEPT-CHARSET", "ACCEPT-ENCODING",
+ "ACCESS-CONTROL-REQUEST-HEADERS", "ACCESS-CONTROL-REQUEST-METHOD",
+ "CONNECTION", "CONTENT-LENGTH", "COOKIE", "COOKIE2", "DATE", "DNT",
+ "EXPECT", "HOST", "KEEP-ALIVE", "ORIGIN", "REFERER", "TE", "TRAILER",
+ "TRANSFER-ENCODING", "UPGRADE", "VIA"];
+
+const FORBIDDEN_PREFIXES = /^PROXY-|^SEC-/i;
+
+class DownloadItem {
+ constructor(id, download, extension) {
+ this.id = id;
+ this.download = download;
+ this.extension = extension;
+ this.prechange = {};
+ }
+
+ get url() { return this.download.source.url; }
+ get referrer() { return this.download.source.referrer; }
+ get filename() { return this.download.target.path; }
+ get incognito() { return this.download.source.isPrivate; }
+ get danger() { return "safe"; } // TODO
+ get mime() { return this.download.contentType; }
+ get startTime() { return this.download.startTime; }
+ get endTime() { return null; } // TODO
+ get estimatedEndTime() { return null; } // TODO
+ get state() {
+ if (this.download.succeeded) {
+ return "complete";
+ }
+ if (this.download.canceled) {
+ return "interrupted";
+ }
+ return "in_progress";
+ }
+ get paused() {
+ return this.download.canceled && this.download.hasPartialData && !this.download.error;
+ }
+ get canResume() {
+ return (this.download.stopped || this.download.canceled) &&
+ this.download.hasPartialData && !this.download.error;
+ }
+ get error() {
+ if (!this.download.stopped || this.download.succeeded) {
+ return null;
+ }
+ // TODO store this instead of calculating it
+
+ if (this.download.error) {
+ if (this.download.error.becauseSourceFailed) {
+ return "NETWORK_FAILED"; // TODO
+ }
+ if (this.download.error.becauseTargetFailed) {
+ return "FILE_FAILED"; // TODO
+ }
+ return "CRASH";
+ }
+ return "USER_CANCELED";
+ }
+ get bytesReceived() {
+ return this.download.currentBytes;
+ }
+ get totalBytes() {
+ return this.download.hasProgress ? this.download.totalBytes : -1;
+ }
+ get fileSize() {
+ // todo: this is supposed to be post-compression
+ return this.download.succeeded ? this.download.target.size : -1;
+ }
+ get exists() { return this.download.target.exists; }
+ get byExtensionId() { return this.extension ? this.extension.id : undefined; }
+ get byExtensionName() { return this.extension ? this.extension.name : undefined; }
+
+ /**
+ * Create a cloneable version of this object by pulling all the
+ * fields into simple properties (instead of getters).
+ *
+ * @returns {object} A DownloadItem with flat properties,
+ * suitable for cloning.
+ */
+ serialize() {
+ let obj = {};
+ for (let field of DOWNLOAD_ITEM_FIELDS) {
+ obj[field] = this[field];
+ }
+ if (obj.startTime) {
+ obj.startTime = obj.startTime.toISOString();
+ }
+ return obj;
+ }
+
+ // When a change event fires, handlers can look at how an individual
+ // field changed by comparing item.fieldname with item.prechange.fieldname.
+ // After all handlers have been invoked, this gets called to store the
+ // current values of all fields ahead of the next event.
+ _change() {
+ for (let field of DOWNLOAD_ITEM_CHANGE_FIELDS) {
+ this.prechange[field] = this[field];
+ }
+ }
+}
+
+
+// DownloadMap maps back and forth betwen the numeric identifiers used in
+// the downloads WebExtension API and a Download object from the Downloads jsm.
+// todo: make id and extension info persistent (bug 1247794)
+const DownloadMap = {
+ currentId: 0,
+ loadPromise: null,
+
+ // Maps numeric id -> DownloadItem
+ byId: new Map(),
+
+ // Maps Download object -> DownloadItem
+ byDownload: new WeakMap(),
+
+ lazyInit() {
+ if (this.loadPromise == null) {
+ EventEmitter.decorate(this);
+ this.loadPromise = Downloads.getList(Downloads.ALL).then(list => {
+ let self = this;
+ return list.addView({
+ onDownloadAdded(download) {
+ const item = self.newFromDownload(download, null);
+ self.emit("create", item);
+ },
+
+ onDownloadRemoved(download) {
+ const item = self.byDownload.get(download);
+ if (item != null) {
+ self.emit("erase", item);
+ self.byDownload.delete(download);
+ self.byId.delete(item.id);
+ }
+ },
+
+ onDownloadChanged(download) {
+ const item = self.byDownload.get(download);
+ if (item == null) {
+ Cu.reportError("Got onDownloadChanged for unknown download object");
+ } else {
+ // We get the first one of these when the download is started.
+ // In this case, don't emit anything, just initialize prechange.
+ if (Object.keys(item.prechange).length > 0) {
+ self.emit("change", item);
+ }
+ item._change();
+ }
+ },
+ }).then(() => list.getAll())
+ .then(downloads => {
+ downloads.forEach(download => {
+ this.newFromDownload(download, null);
+ });
+ })
+ .then(() => list);
+ });
+ }
+ return this.loadPromise;
+ },
+
+ getDownloadList() {
+ return this.lazyInit();
+ },
+
+ getAll() {
+ return this.lazyInit().then(() => this.byId.values());
+ },
+
+ fromId(id) {
+ const download = this.byId.get(id);
+ if (!download) {
+ throw new Error(`Invalid download id ${id}`);
+ }
+ return download;
+ },
+
+ newFromDownload(download, extension) {
+ if (this.byDownload.has(download)) {
+ return this.byDownload.get(download);
+ }
+
+ const id = ++this.currentId;
+ let item = new DownloadItem(id, download, extension);
+ this.byId.set(id, item);
+ this.byDownload.set(download, item);
+ return item;
+ },
+
+ erase(item) {
+ // This will need to get more complicated for bug 1255507 but for now we
+ // only work with downloads in the DownloadList from getAll()
+ return this.getDownloadList().then(list => {
+ list.remove(item.download);
+ });
+ },
+};
+
+// Create a callable function that filters a DownloadItem based on a
+// query object of the type passed to search() or erase().
+function downloadQuery(query) {
+ let queryTerms = [];
+ let queryNegativeTerms = [];
+ if (query.query != null) {
+ for (let term of query.query) {
+ if (term[0] == "-") {
+ queryNegativeTerms.push(term.slice(1).toLowerCase());
+ } else {
+ queryTerms.push(term.toLowerCase());
+ }
+ }
+ }
+
+ function normalizeDownloadTime(arg, before) {
+ if (arg == null) {
+ return before ? Number.MAX_VALUE : 0;
+ }
+ return normalizeTime(arg).getTime();
+ }
+
+ const startedBefore = normalizeDownloadTime(query.startedBefore, true);
+ const startedAfter = normalizeDownloadTime(query.startedAfter, false);
+ // const endedBefore = normalizeDownloadTime(query.endedBefore, true);
+ // const endedAfter = normalizeDownloadTime(query.endedAfter, false);
+
+ const totalBytesGreater = query.totalBytesGreater || 0;
+ const totalBytesLess = (query.totalBytesLess != null)
+ ? query.totalBytesLess : Number.MAX_VALUE;
+
+ // Handle options for which we can have a regular expression and/or
+ // an explicit value to match.
+ function makeMatch(regex, value, field) {
+ if (value == null && regex == null) {
+ return input => true;
+ }
+
+ let re;
+ try {
+ re = new RegExp(regex || "", "i");
+ } catch (err) {
+ throw new Error(`Invalid ${field}Regex: ${err.message}`);
+ }
+ if (value == null) {
+ return input => re.test(input);
+ }
+
+ value = value.toLowerCase();
+ if (re.test(value)) {
+ return input => (value == input);
+ }
+ return input => false;
+ }
+
+ const matchFilename = makeMatch(query.filenameRegex, query.filename, "filename");
+ const matchUrl = makeMatch(query.urlRegex, query.url, "url");
+
+ return function(item) {
+ const url = item.url.toLowerCase();
+ const filename = item.filename.toLowerCase();
+
+ if (!queryTerms.every(term => url.includes(term) || filename.includes(term))) {
+ return false;
+ }
+
+ if (queryNegativeTerms.some(term => url.includes(term) || filename.includes(term))) {
+ return false;
+ }
+
+ if (!matchFilename(filename) || !matchUrl(url)) {
+ return false;
+ }
+
+ if (!item.startTime) {
+ if (query.startedBefore != null || query.startedAfter != null) {
+ return false;
+ }
+ } else if (item.startTime > startedBefore || item.startTime < startedAfter) {
+ return false;
+ }
+
+ // todo endedBefore, endedAfter
+
+ if (item.totalBytes == -1) {
+ if (query.totalBytesGreater != null || query.totalBytesLess != null) {
+ return false;
+ }
+ } else if (item.totalBytes <= totalBytesGreater || item.totalBytes >= totalBytesLess) {
+ return false;
+ }
+
+ // todo: include danger
+ const SIMPLE_ITEMS = ["id", "mime", "startTime", "endTime", "state",
+ "paused", "error",
+ "bytesReceived", "totalBytes", "fileSize", "exists"];
+ for (let field of SIMPLE_ITEMS) {
+ if (query[field] != null && item[field] != query[field]) {
+ return false;
+ }
+ }
+
+ return true;
+ };
+}
+
+function queryHelper(query) {
+ let matchFn;
+ try {
+ matchFn = downloadQuery(query);
+ } catch (err) {
+ return Promise.reject({message: err.message});
+ }
+
+ let compareFn;
+ if (query.orderBy != null) {
+ const fields = query.orderBy.map(field => field[0] == "-"
+ ? {reverse: true, name: field.slice(1)}
+ : {reverse: false, name: field});
+
+ for (let field of fields) {
+ if (!DOWNLOAD_ITEM_FIELDS.includes(field.name)) {
+ return Promise.reject({message: `Invalid orderBy field ${field.name}`});
+ }
+ }
+
+ compareFn = (dl1, dl2) => {
+ for (let field of fields) {
+ const val1 = dl1[field.name];
+ const val2 = dl2[field.name];
+
+ if (val1 < val2) {
+ return field.reverse ? 1 : -1;
+ } else if (val1 > val2) {
+ return field.reverse ? -1 : 1;
+ }
+ }
+ return 0;
+ };
+ }
+
+ return DownloadMap.getAll().then(downloads => {
+ if (compareFn) {
+ downloads = Array.from(downloads);
+ downloads.sort(compareFn);
+ }
+ let results = [];
+ for (let download of downloads) {
+ if (query.limit && results.length >= query.limit) {
+ break;
+ }
+ if (matchFn(download)) {
+ results.push(download);
+ }
+ }
+ return results;
+ });
+}
+
+extensions.registerSchemaAPI("downloads", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ downloads: {
+ download(options) {
+ let {filename} = options;
+ if (filename && PlatformInfo.os === "win") {
+ // cross platform javascript code uses "/"
+ filename = filename.replace(/\//g, "\\");
+ }
+
+ if (filename != null) {
+ if (filename.length == 0) {
+ return Promise.reject({message: "filename must not be empty"});
+ }
+
+ let path = OS.Path.split(filename);
+ if (path.absolute) {
+ return Promise.reject({message: "filename must not be an absolute path"});
+ }
+
+ if (path.components.some(component => component == "..")) {
+ return Promise.reject({message: "filename must not contain back-references (..)"});
+ }
+ }
+
+ if (options.conflictAction == "prompt") {
+ // TODO
+ return Promise.reject({message: "conflictAction prompt not yet implemented"});
+ }
+
+ if (options.headers) {
+ for (let {name} of options.headers) {
+ if (FORBIDDEN_HEADERS.includes(name.toUpperCase()) || name.match(FORBIDDEN_PREFIXES)) {
+ return Promise.reject({message: "Forbidden request header name"});
+ }
+ }
+ }
+
+ // Handle method, headers and body options.
+ function adjustChannel(channel) {
+ if (channel instanceof Ci.nsIHttpChannel) {
+ const method = options.method || "GET";
+ channel.requestMethod = method;
+
+ if (options.headers) {
+ for (let {name, value} of options.headers) {
+ channel.setRequestHeader(name, value, false);
+ }
+ }
+
+ if (options.body != null) {
+ const stream = Cc["@mozilla.org/io/string-input-stream;1"]
+ .createInstance(Ci.nsIStringInputStream);
+ stream.setData(options.body, options.body.length);
+
+ channel.QueryInterface(Ci.nsIUploadChannel2);
+ channel.explicitSetUploadStream(stream, null, -1, method, false);
+ }
+ }
+ return Promise.resolve();
+ }
+
+ function createTarget(downloadsDir) {
+ let target;
+ if (filename) {
+ target = OS.Path.join(downloadsDir, filename);
+ } else {
+ let uri = NetUtil.newURI(options.url);
+
+ let remote = "download";
+ if (uri instanceof Ci.nsIURL) {
+ remote = uri.fileName;
+ }
+ target = OS.Path.join(downloadsDir, remote);
+ }
+
+ // Create any needed subdirectories if required by filename.
+ const dir = OS.Path.dirname(target);
+ return OS.File.makeDir(dir, {from: downloadsDir}).then(() => {
+ return OS.File.exists(target);
+ }).then(exists => {
+ // This has a race, something else could come along and create
+ // the file between this test and them time the download code
+ // creates the target file. But we can't easily fix it without
+ // modifying DownloadCore so we live with it for now.
+ if (exists) {
+ switch (options.conflictAction) {
+ case "uniquify":
+ default:
+ target = DownloadPaths.createNiceUniqueFile(new FileUtils.File(target)).path;
+ break;
+
+ case "overwrite":
+ break;
+ }
+ }
+ }).then(() => {
+ if (!options.saveAs) {
+ return Promise.resolve(target);
+ }
+
+ // Setup the file picker Save As dialog.
+ const picker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
+ const window = Services.wm.getMostRecentWindow("navigator:browser");
+ picker.init(window, null, Ci.nsIFilePicker.modeSave);
+ picker.displayDirectory = new FileUtils.File(dir);
+ picker.appendFilters(Ci.nsIFilePicker.filterAll);
+ picker.defaultString = OS.Path.basename(target);
+
+ // Open the dialog and resolve/reject with the result.
+ return new Promise((resolve, reject) => {
+ picker.open(result => {
+ if (result === Ci.nsIFilePicker.returnCancel) {
+ reject({message: "Download canceled by the user"});
+ } else {
+ resolve(picker.file.path);
+ }
+ });
+ });
+ });
+ }
+
+ let download;
+ return Downloads.getPreferredDownloadsDirectory()
+ .then(downloadsDir => createTarget(downloadsDir))
+ .then(target => {
+ const source = {
+ url: options.url,
+ };
+
+ if (options.method || options.headers || options.body) {
+ source.adjustChannel = adjustChannel;
+ }
+
+ return Downloads.createDownload({
+ source,
+ target: {
+ path: target,
+ partFilePath: target + ".part",
+ },
+ });
+ }).then(dl => {
+ download = dl;
+ return DownloadMap.getDownloadList();
+ }).then(list => {
+ list.add(download);
+
+ // This is necessary to make pause/resume work.
+ download.tryToKeepPartialData = true;
+ download.start();
+
+ const item = DownloadMap.newFromDownload(download, extension);
+ return item.id;
+ });
+ },
+
+ removeFile(id) {
+ return DownloadMap.lazyInit().then(() => {
+ let item;
+ try {
+ item = DownloadMap.fromId(id);
+ } catch (err) {
+ return Promise.reject({message: `Invalid download id ${id}`});
+ }
+ if (item.state !== "complete") {
+ return Promise.reject({message: `Cannot remove incomplete download id ${id}`});
+ }
+ return OS.File.remove(item.filename, {ignoreAbsent: false}).catch((err) => {
+ return Promise.reject({message: `Could not remove download id ${item.id} because the file doesn't exist`});
+ });
+ });
+ },
+
+ search(query) {
+ return queryHelper(query)
+ .then(items => items.map(item => item.serialize()));
+ },
+
+ pause(id) {
+ return DownloadMap.lazyInit().then(() => {
+ let item;
+ try {
+ item = DownloadMap.fromId(id);
+ } catch (err) {
+ return Promise.reject({message: `Invalid download id ${id}`});
+ }
+ if (item.state != "in_progress") {
+ return Promise.reject({message: `Download ${id} cannot be paused since it is in state ${item.state}`});
+ }
+
+ return item.download.cancel();
+ });
+ },
+
+ resume(id) {
+ return DownloadMap.lazyInit().then(() => {
+ let item;
+ try {
+ item = DownloadMap.fromId(id);
+ } catch (err) {
+ return Promise.reject({message: `Invalid download id ${id}`});
+ }
+ if (!item.canResume) {
+ return Promise.reject({message: `Download ${id} cannot be resumed`});
+ }
+
+ return item.download.start();
+ });
+ },
+
+ cancel(id) {
+ return DownloadMap.lazyInit().then(() => {
+ let item;
+ try {
+ item = DownloadMap.fromId(id);
+ } catch (err) {
+ return Promise.reject({message: `Invalid download id ${id}`});
+ }
+ if (item.download.succeeded) {
+ return Promise.reject({message: `Download ${id} is already complete`});
+ }
+ return item.download.finalize(true);
+ });
+ },
+
+ showDefaultFolder() {
+ Downloads.getPreferredDownloadsDirectory().then(dir => {
+ let dirobj = new FileUtils.File(dir);
+ if (dirobj.isDirectory()) {
+ dirobj.launch();
+ } else {
+ throw new Error(`Download directory ${dirobj.path} is not actually a directory`);
+ }
+ }).catch(Cu.reportError);
+ },
+
+ erase(query) {
+ return queryHelper(query).then(items => {
+ let results = [];
+ let promises = [];
+ for (let item of items) {
+ promises.push(DownloadMap.erase(item));
+ results.push(item.id);
+ }
+ return Promise.all(promises).then(() => results);
+ });
+ },
+
+ open(downloadId) {
+ return DownloadMap.lazyInit().then(() => {
+ let download = DownloadMap.fromId(downloadId).download;
+ if (download.succeeded) {
+ return download.launch();
+ }
+ return Promise.reject({message: "Download has not completed."});
+ }).catch((error) => {
+ return Promise.reject({message: error.message});
+ });
+ },
+
+ show(downloadId) {
+ return DownloadMap.lazyInit().then(() => {
+ let download = DownloadMap.fromId(downloadId);
+ return download.download.showContainingDirectory();
+ }).then(() => {
+ return true;
+ }).catch(error => {
+ return Promise.reject({message: error.message});
+ });
+ },
+
+ getFileIcon(downloadId, options) {
+ return DownloadMap.lazyInit().then(() => {
+ let size = options && options.size ? options.size : 32;
+ let download = DownloadMap.fromId(downloadId).download;
+ let pathPrefix = "";
+ let path;
+
+ if (download.succeeded) {
+ let file = FileUtils.File(download.target.path);
+ path = Services.io.newFileURI(file).spec;
+ } else {
+ path = OS.Path.basename(download.target.path);
+ pathPrefix = "//";
+ }
+
+ return new Promise((resolve, reject) => {
+ let chromeWebNav = Services.appShell.createWindowlessBrowser(true);
+ chromeWebNav
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell)
+ .createAboutBlankContentViewer(Services.scriptSecurityManager.getSystemPrincipal());
+
+ let img = chromeWebNav.document.createElement("img");
+ img.width = size;
+ img.height = size;
+
+ let handleLoad;
+ let handleError;
+ const cleanup = () => {
+ img.removeEventListener("load", handleLoad);
+ img.removeEventListener("error", handleError);
+ chromeWebNav.close();
+ chromeWebNav = null;
+ };
+
+ handleLoad = () => {
+ let canvas = chromeWebNav.document.createElement("canvas");
+ canvas.width = size;
+ canvas.height = size;
+ let context = canvas.getContext("2d");
+ context.drawImage(img, 0, 0, size, size);
+ let dataURL = canvas.toDataURL("image/png");
+ cleanup();
+ resolve(dataURL);
+ };
+
+ handleError = (error) => {
+ Cu.reportError(error);
+ cleanup();
+ reject(new Error("An unexpected error occurred"));
+ };
+
+ img.addEventListener("load", handleLoad);
+ img.addEventListener("error", handleError);
+ img.src = `moz-icon:${pathPrefix}${path}?size=${size}`;
+ });
+ }).catch((error) => {
+ return Promise.reject({message: error.message});
+ });
+ },
+
+ // When we do setShelfEnabled(), check for additional "downloads.shelf" permission.
+ // i.e.:
+ // setShelfEnabled(enabled) {
+ // if (!extension.hasPermission("downloads.shelf")) {
+ // throw new context.cloneScope.Error("Permission denied because 'downloads.shelf' permission is missing.");
+ // }
+ // ...
+ // }
+
+ onChanged: new SingletonEventManager(context, "downloads.onChanged", fire => {
+ const handler = (what, item) => {
+ let changes = {};
+ const noundef = val => (val === undefined) ? null : val;
+ DOWNLOAD_ITEM_CHANGE_FIELDS.forEach(fld => {
+ if (item[fld] != item.prechange[fld]) {
+ changes[fld] = {
+ previous: noundef(item.prechange[fld]),
+ current: noundef(item[fld]),
+ };
+ }
+ });
+ if (Object.keys(changes).length > 0) {
+ changes.id = item.id;
+ runSafeSync(context, fire, changes);
+ }
+ };
+
+ let registerPromise = DownloadMap.getDownloadList().then(() => {
+ DownloadMap.on("change", handler);
+ });
+ return () => {
+ registerPromise.then(() => {
+ DownloadMap.off("change", handler);
+ });
+ };
+ }).api(),
+
+ onCreated: new SingletonEventManager(context, "downloads.onCreated", fire => {
+ const handler = (what, item) => {
+ runSafeSync(context, fire, item.serialize());
+ };
+ let registerPromise = DownloadMap.getDownloadList().then(() => {
+ DownloadMap.on("create", handler);
+ });
+ return () => {
+ registerPromise.then(() => {
+ DownloadMap.off("create", handler);
+ });
+ };
+ }).api(),
+
+ onErased: new SingletonEventManager(context, "downloads.onErased", fire => {
+ const handler = (what, item) => {
+ runSafeSync(context, fire, item.id);
+ };
+ let registerPromise = DownloadMap.getDownloadList().then(() => {
+ DownloadMap.on("erase", handler);
+ });
+ return () => {
+ registerPromise.then(() => {
+ DownloadMap.off("erase", handler);
+ });
+ };
+ }).api(),
+
+ onDeterminingFilename: ignoreEvent(context, "downloads.onDeterminingFilename"),
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-extension.js b/toolkit/components/webextensions/ext-extension.js
new file mode 100644
index 000000000..c4bdc8b63
--- /dev/null
+++ b/toolkit/components/webextensions/ext-extension.js
@@ -0,0 +1,20 @@
+"use strict";
+
+extensions.registerSchemaAPI("extension", "addon_parent", context => {
+ return {
+ extension: {
+ get lastError() {
+ return context.lastError;
+ },
+
+ isAllowedIncognitoAccess() {
+ return Promise.resolve(true);
+ },
+
+ isAllowedFileSchemeAccess() {
+ return Promise.resolve(false);
+ },
+ },
+ };
+});
+
diff --git a/toolkit/components/webextensions/ext-i18n.js b/toolkit/components/webextensions/ext-i18n.js
new file mode 100644
index 000000000..bb4bde4bd
--- /dev/null
+++ b/toolkit/components/webextensions/ext-i18n.js
@@ -0,0 +1,34 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ detectLanguage,
+} = ExtensionUtils;
+
+function i18nApiFactory(context) {
+ let {extension} = context;
+ return {
+ i18n: {
+ getMessage: function(messageName, substitutions) {
+ return extension.localizeMessage(messageName, substitutions, {cloneScope: context.cloneScope});
+ },
+
+ getAcceptLanguages: function() {
+ let result = extension.localeData.acceptLanguages;
+ return Promise.resolve(result);
+ },
+
+ getUILanguage: function() {
+ return extension.localeData.uiLocale;
+ },
+
+ detectLanguage: function(text) {
+ return detectLanguage(text);
+ },
+ },
+ };
+}
+extensions.registerSchemaAPI("i18n", "addon_child", i18nApiFactory);
+extensions.registerSchemaAPI("i18n", "content_child", i18nApiFactory);
diff --git a/toolkit/components/webextensions/ext-idle.js b/toolkit/components/webextensions/ext-idle.js
new file mode 100644
index 000000000..c5be4b600
--- /dev/null
+++ b/toolkit/components/webextensions/ext-idle.js
@@ -0,0 +1,94 @@
+"use strict";
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter",
+ "resource://devtools/shared/event-emitter.js");
+XPCOMUtils.defineLazyServiceGetter(this, "idleService",
+ "@mozilla.org/widget/idleservice;1",
+ "nsIIdleService");
+const {
+ SingletonEventManager,
+} = ExtensionUtils;
+
+// WeakMap[Extension -> Object]
+var observersMap = new WeakMap();
+
+function getObserverInfo(extension, context) {
+ let observerInfo = observersMap.get(extension);
+ if (!observerInfo) {
+ observerInfo = {
+ observer: null,
+ detectionInterval: 60,
+ };
+ observersMap.set(extension, observerInfo);
+ context.callOnClose({
+ close: () => {
+ let {observer, detectionInterval} = observersMap.get(extension);
+ if (observer) {
+ idleService.removeIdleObserver(observer, detectionInterval);
+ }
+ observersMap.delete(extension);
+ },
+ });
+ }
+ return observerInfo;
+}
+
+function getObserver(extension, context) {
+ let observerInfo = getObserverInfo(extension, context);
+ let {observer, detectionInterval} = observerInfo;
+ if (!observer) {
+ observer = {
+ observe: function(subject, topic, data) {
+ if (topic == "idle" || topic == "active") {
+ this.emit("stateChanged", topic);
+ }
+ },
+ };
+ EventEmitter.decorate(observer);
+ idleService.addIdleObserver(observer, detectionInterval);
+ observerInfo.observer = observer;
+ observerInfo.detectionInterval = detectionInterval;
+ }
+ return observer;
+}
+
+function setDetectionInterval(extension, context, newInterval) {
+ let observerInfo = getObserverInfo(extension, context);
+ let {observer, detectionInterval} = observerInfo;
+ if (observer) {
+ idleService.removeIdleObserver(observer, detectionInterval);
+ idleService.addIdleObserver(observer, newInterval);
+ }
+ observerInfo.detectionInterval = newInterval;
+}
+
+extensions.registerSchemaAPI("idle", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ idle: {
+ queryState: function(detectionIntervalInSeconds) {
+ if (idleService.idleTime < detectionIntervalInSeconds * 1000) {
+ return Promise.resolve("active");
+ }
+ return Promise.resolve("idle");
+ },
+ setDetectionInterval: function(detectionIntervalInSeconds) {
+ setDetectionInterval(extension, context, detectionIntervalInSeconds);
+ },
+ onStateChanged: new SingletonEventManager(context, "idle.onStateChanged", fire => {
+ let listener = (event, data) => {
+ context.runSafe(fire, data);
+ };
+
+ getObserver(extension, context).on("stateChanged", listener);
+ return () => {
+ getObserver(extension, context).off("stateChanged", listener);
+ };
+ }).api(),
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-management.js b/toolkit/components/webextensions/ext-management.js
new file mode 100644
index 000000000..59a7959d7
--- /dev/null
+++ b/toolkit/components/webextensions/ext-management.js
@@ -0,0 +1,109 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+XPCOMUtils.defineLazyGetter(this, "strBundle", function() {
+ const stringSvc = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
+ return stringSvc.createBundle("chrome://global/locale/extensions.properties");
+});
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyServiceGetter(this, "promptService",
+ "@mozilla.org/embedcomp/prompt-service;1",
+ "nsIPromptService");
+
+function _(key, ...args) {
+ if (args.length) {
+ return strBundle.formatStringFromName(key, args, args.length);
+ }
+ return strBundle.GetStringFromName(key);
+}
+
+function installType(addon) {
+ if (addon.temporarilyInstalled) {
+ return "development";
+ } else if (addon.foreignInstall) {
+ return "sideload";
+ } else if (addon.isSystem) {
+ return "other";
+ }
+ return "normal";
+}
+
+extensions.registerSchemaAPI("management", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ management: {
+ getSelf: function() {
+ return new Promise((resolve, reject) => AddonManager.getAddonByID(extension.id, addon => {
+ try {
+ let m = extension.manifest;
+ let extInfo = {
+ id: extension.id,
+ name: addon.name,
+ shortName: m.short_name || "",
+ description: addon.description || "",
+ version: addon.version,
+ mayDisable: !!(addon.permissions & AddonManager.PERM_CAN_DISABLE),
+ enabled: addon.isActive,
+ optionsUrl: addon.optionsURL || "",
+ permissions: Array.from(extension.permissions).filter(perm => {
+ return !extension.whiteListedHosts.pat.includes(perm);
+ }),
+ hostPermissions: extension.whiteListedHosts.pat,
+ installType: installType(addon),
+ };
+ if (addon.homepageURL) {
+ extInfo.homepageUrl = addon.homepageURL;
+ }
+ if (addon.updateURL) {
+ extInfo.updateUrl = addon.updateURL;
+ }
+ if (m.icons) {
+ extInfo.icons = Object.keys(m.icons).map(key => {
+ return {size: Number(key), url: m.icons[key]};
+ });
+ }
+
+ resolve(extInfo);
+ } catch (err) {
+ reject(err);
+ }
+ }));
+ },
+
+ uninstallSelf: function(options) {
+ return new Promise((resolve, reject) => {
+ if (options && options.showConfirmDialog) {
+ let message = _("uninstall.confirmation.message", extension.name);
+ if (options.dialogMessage) {
+ message = `${options.dialogMessage}\n${message}`;
+ }
+ let title = _("uninstall.confirmation.title", extension.name);
+ let buttonFlags = promptService.BUTTON_POS_0 * promptService.BUTTON_TITLE_IS_STRING +
+ promptService.BUTTON_POS_1 * promptService.BUTTON_TITLE_IS_STRING;
+ let button0Title = _("uninstall.confirmation.button-0.label");
+ let button1Title = _("uninstall.confirmation.button-1.label");
+ let response = promptService.confirmEx(null, title, message, buttonFlags, button0Title, button1Title, null, null, {value: 0});
+ if (response == 1) {
+ return reject({message: "User cancelled uninstall of extension"});
+ }
+ }
+ AddonManager.getAddonByID(extension.id, addon => {
+ let canUninstall = Boolean(addon.permissions & AddonManager.PERM_CAN_UNINSTALL);
+ if (!canUninstall) {
+ return reject({message: "The add-on cannot be uninstalled"});
+ }
+ try {
+ addon.uninstall();
+ } catch (err) {
+ return reject(err);
+ }
+ });
+ });
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-notifications.js b/toolkit/components/webextensions/ext-notifications.js
new file mode 100644
index 000000000..1df96a2ac
--- /dev/null
+++ b/toolkit/components/webextensions/ext-notifications.js
@@ -0,0 +1,161 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter",
+ "resource://devtools/shared/event-emitter.js");
+
+var {
+ EventManager,
+ ignoreEvent,
+} = ExtensionUtils;
+
+// WeakMap[Extension -> Map[id -> Notification]]
+var notificationsMap = new WeakMap();
+
+// Manages a notification popup (notifications API) created by the extension.
+function Notification(extension, id, options) {
+ this.extension = extension;
+ this.id = id;
+ this.options = options;
+
+ let imageURL;
+ if (options.iconUrl) {
+ imageURL = this.extension.baseURI.resolve(options.iconUrl);
+ }
+
+ try {
+ let svc = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
+ svc.showAlertNotification(imageURL,
+ options.title,
+ options.message,
+ true, // textClickable
+ this.id,
+ this,
+ this.id);
+ } catch (e) {
+ // This will fail if alerts aren't available on the system.
+ }
+}
+
+Notification.prototype = {
+ clear() {
+ try {
+ let svc = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService);
+ svc.closeAlert(this.id);
+ } catch (e) {
+ // This will fail if the OS doesn't support this function.
+ }
+ notificationsMap.get(this.extension).delete(this.id);
+ },
+
+ observe(subject, topic, data) {
+ let notifications = notificationsMap.get(this.extension);
+
+ let emitAndDelete = event => {
+ notifications.emit(event, data);
+ notifications.delete(this.id);
+ };
+
+ // Don't try to emit events if the extension has been unloaded
+ if (!notifications) {
+ return;
+ }
+
+ if (topic === "alertclickcallback") {
+ emitAndDelete("clicked");
+ }
+ if (topic === "alertfinished") {
+ emitAndDelete("closed");
+ }
+ },
+};
+
+/* eslint-disable mozilla/balanced-listeners */
+extensions.on("startup", (type, extension) => {
+ let map = new Map();
+ EventEmitter.decorate(map);
+ notificationsMap.set(extension, map);
+});
+
+extensions.on("shutdown", (type, extension) => {
+ if (notificationsMap.has(extension)) {
+ for (let notification of notificationsMap.get(extension).values()) {
+ notification.clear();
+ }
+ notificationsMap.delete(extension);
+ }
+});
+/* eslint-enable mozilla/balanced-listeners */
+
+var nextId = 0;
+
+extensions.registerSchemaAPI("notifications", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ notifications: {
+ create: function(notificationId, options) {
+ if (!notificationId) {
+ notificationId = String(nextId++);
+ }
+
+ let notifications = notificationsMap.get(extension);
+ if (notifications.has(notificationId)) {
+ notifications.get(notificationId).clear();
+ }
+
+ // FIXME: Lots of options still aren't supported, especially
+ // buttons.
+ let notification = new Notification(extension, notificationId, options);
+ notificationsMap.get(extension).set(notificationId, notification);
+
+ return Promise.resolve(notificationId);
+ },
+
+ clear: function(notificationId) {
+ let notifications = notificationsMap.get(extension);
+ if (notifications.has(notificationId)) {
+ notifications.get(notificationId).clear();
+ return Promise.resolve(true);
+ }
+ return Promise.resolve(false);
+ },
+
+ getAll: function() {
+ let result = {};
+ notificationsMap.get(extension).forEach((value, key) => {
+ result[key] = value.options;
+ });
+ return Promise.resolve(result);
+ },
+
+ onClosed: new EventManager(context, "notifications.onClosed", fire => {
+ let listener = (event, notificationId) => {
+ // FIXME: Support the byUser argument.
+ fire(notificationId, true);
+ };
+
+ notificationsMap.get(extension).on("closed", listener);
+ return () => {
+ notificationsMap.get(extension).off("closed", listener);
+ };
+ }).api(),
+
+ onClicked: new EventManager(context, "notifications.onClicked", fire => {
+ let listener = (event, notificationId) => {
+ fire(notificationId, true);
+ };
+
+ notificationsMap.get(extension).on("clicked", listener);
+ return () => {
+ notificationsMap.get(extension).off("clicked", listener);
+ };
+ }).api(),
+
+ // Intend to implement this later: https://bugzilla.mozilla.org/show_bug.cgi?id=1190681
+ onButtonClicked: ignoreEvent(context, "notifications.onButtonClicked"),
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-runtime.js b/toolkit/components/webextensions/ext-runtime.js
new file mode 100644
index 000000000..aed3ffd4b
--- /dev/null
+++ b/toolkit/components/webextensions/ext-runtime.js
@@ -0,0 +1,134 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Extension",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
+ "resource://gre/modules/ExtensionManagement.jsm");
+
+var {
+ SingletonEventManager,
+} = ExtensionUtils;
+
+extensions.registerSchemaAPI("runtime", "addon_parent", context => {
+ let {extension} = context;
+ return {
+ runtime: {
+ onStartup: new SingletonEventManager(context, "runtime.onStartup", fire => {
+ if (context.incognito) {
+ // This event should not fire if we are operating in a private profile.
+ return () => {};
+ }
+ let listener = () => {
+ if (extension.startupReason === "APP_STARTUP") {
+ fire();
+ }
+ };
+ extension.on("startup", listener);
+ return () => {
+ extension.off("startup", listener);
+ };
+ }).api(),
+
+ onInstalled: new SingletonEventManager(context, "runtime.onInstalled", fire => {
+ let listener = () => {
+ switch (extension.startupReason) {
+ case "APP_STARTUP":
+ if (Extension.browserUpdated) {
+ fire({reason: "browser_update"});
+ }
+ break;
+ case "ADDON_INSTALL":
+ fire({reason: "install"});
+ break;
+ case "ADDON_UPGRADE":
+ fire({reason: "update"});
+ break;
+ }
+ };
+ extension.on("startup", listener);
+ return () => {
+ extension.off("startup", listener);
+ };
+ }).api(),
+
+ onUpdateAvailable: new SingletonEventManager(context, "runtime.onUpdateAvailable", fire => {
+ let instanceID = extension.addonData.instanceID;
+ AddonManager.addUpgradeListener(instanceID, upgrade => {
+ extension.upgrade = upgrade;
+ let details = {
+ version: upgrade.version,
+ };
+ context.runSafe(fire, details);
+ });
+ return () => {
+ AddonManager.removeUpgradeListener(instanceID);
+ };
+ }).api(),
+
+ reload: () => {
+ if (extension.upgrade) {
+ // If there is a pending update, install it now.
+ extension.upgrade.install();
+ } else {
+ // Otherwise, reload the current extension.
+ AddonManager.getAddonByID(extension.id, addon => {
+ addon.reload();
+ });
+ }
+ },
+
+ get lastError() {
+ // TODO(robwu): Figure out how to make sure that errors in the parent
+ // process are propagated to the child process.
+ // lastError should not be accessed from the parent.
+ return context.lastError;
+ },
+
+ getBrowserInfo: function() {
+ const {name, vendor, version, appBuildID} = Services.appinfo;
+ const info = {name, vendor, version, buildID: appBuildID};
+ return Promise.resolve(info);
+ },
+
+ getPlatformInfo: function() {
+ return Promise.resolve(ExtensionUtils.PlatformInfo);
+ },
+
+ openOptionsPage: function() {
+ if (!extension.manifest.options_ui) {
+ return Promise.reject({message: "No `options_ui` declared"});
+ }
+
+ return openOptionsPage(extension).then(() => {});
+ },
+
+ setUninstallURL: function(url) {
+ if (url.length == 0) {
+ return Promise.resolve();
+ }
+
+ let uri;
+ try {
+ uri = NetUtil.newURI(url);
+ } catch (e) {
+ return Promise.reject({message: `Invalid URL: ${JSON.stringify(url)}`});
+ }
+
+ if (uri.scheme != "http" && uri.scheme != "https") {
+ return Promise.reject({message: "url must have the scheme http or https"});
+ }
+
+ extension.uninstallURL = url;
+ return Promise.resolve();
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-storage.js b/toolkit/components/webextensions/ext-storage.js
new file mode 100644
index 000000000..b1e22c46c
--- /dev/null
+++ b/toolkit/components/webextensions/ext-storage.js
@@ -0,0 +1,46 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage",
+ "resource://gre/modules/ExtensionStorage.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ EventManager,
+} = ExtensionUtils;
+
+function storageApiFactory(context) {
+ let {extension} = context;
+ return {
+ storage: {
+ local: {
+ get: function(spec) {
+ return ExtensionStorage.get(extension.id, spec);
+ },
+ set: function(items) {
+ return ExtensionStorage.set(extension.id, items, context);
+ },
+ remove: function(keys) {
+ return ExtensionStorage.remove(extension.id, keys);
+ },
+ clear: function() {
+ return ExtensionStorage.clear(extension.id);
+ },
+ },
+
+ onChanged: new EventManager(context, "storage.onChanged", fire => {
+ let listenerLocal = changes => {
+ fire(changes, "local");
+ };
+
+ ExtensionStorage.addOnChangedListener(extension.id, listenerLocal);
+ return () => {
+ ExtensionStorage.removeOnChangedListener(extension.id, listenerLocal);
+ };
+ }).api(),
+ },
+ };
+}
+extensions.registerSchemaAPI("storage", "addon_parent", storageApiFactory);
+extensions.registerSchemaAPI("storage", "content_parent", storageApiFactory);
diff --git a/toolkit/components/webextensions/ext-topSites.js b/toolkit/components/webextensions/ext-topSites.js
new file mode 100644
index 000000000..a66ac85d9
--- /dev/null
+++ b/toolkit/components/webextensions/ext-topSites.js
@@ -0,0 +1,24 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm");
+
+extensions.registerSchemaAPI("topSites", "addon_parent", context => {
+ return {
+ topSites: {
+ get: function() {
+ let urls = NewTabUtils.links.getLinks()
+ .filter(link => !!link)
+ .map(link => {
+ return {
+ url: link.url,
+ title: link.title,
+ };
+ });
+ return Promise.resolve(urls);
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-webNavigation.js b/toolkit/components/webextensions/ext-webNavigation.js
new file mode 100644
index 000000000..904f3a4a7
--- /dev/null
+++ b/toolkit/components/webextensions/ext-webNavigation.js
@@ -0,0 +1,192 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
+ "resource://gre/modules/ExtensionManagement.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "MatchURLFilters",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "WebNavigation",
+ "resource://gre/modules/WebNavigation.jsm");
+
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ SingletonEventManager,
+ ignoreEvent,
+} = ExtensionUtils;
+
+const defaultTransitionTypes = {
+ topFrame: "link",
+ subFrame: "auto_subframe",
+};
+
+const frameTransitions = {
+ anyFrame: {
+ qualifiers: ["server_redirect", "client_redirect", "forward_back"],
+ },
+ topFrame: {
+ types: ["reload", "form_submit"],
+ },
+};
+
+const tabTransitions = {
+ topFrame: {
+ qualifiers: ["from_address_bar"],
+ types: ["auto_bookmark", "typed", "keyword", "generated", "link"],
+ },
+ subFrame: {
+ types: ["manual_subframe"],
+ },
+};
+
+function isTopLevelFrame({frameId, parentFrameId}) {
+ return frameId == 0 && parentFrameId == -1;
+}
+
+function fillTransitionProperties(eventName, src, dst) {
+ if (eventName == "onCommitted" || eventName == "onHistoryStateUpdated") {
+ let frameTransitionData = src.frameTransitionData || {};
+ let tabTransitionData = src.tabTransitionData || {};
+
+ let transitionType, transitionQualifiers = [];
+
+ // Fill transition properties for any frame.
+ for (let qualifier of frameTransitions.anyFrame.qualifiers) {
+ if (frameTransitionData[qualifier]) {
+ transitionQualifiers.push(qualifier);
+ }
+ }
+
+ if (isTopLevelFrame(dst)) {
+ for (let type of frameTransitions.topFrame.types) {
+ if (frameTransitionData[type]) {
+ transitionType = type;
+ }
+ }
+
+ for (let qualifier of tabTransitions.topFrame.qualifiers) {
+ if (tabTransitionData[qualifier]) {
+ transitionQualifiers.push(qualifier);
+ }
+ }
+
+ for (let type of tabTransitions.topFrame.types) {
+ if (tabTransitionData[type]) {
+ transitionType = type;
+ }
+ }
+
+ // If transitionType is not defined, defaults it to "link".
+ if (!transitionType) {
+ transitionType = defaultTransitionTypes.topFrame;
+ }
+ } else {
+ // If it is sub-frame, transitionType defaults it to "auto_subframe",
+ // "manual_subframe" is set only in case of a recent user interaction.
+ transitionType = tabTransitionData.link ?
+ "manual_subframe" : defaultTransitionTypes.subFrame;
+ }
+
+ // Fill the transition properties in the webNavigation event object.
+ dst.transitionType = transitionType;
+ dst.transitionQualifiers = transitionQualifiers;
+ }
+}
+
+// Similar to WebRequestEventManager but for WebNavigation.
+function WebNavigationEventManager(context, eventName) {
+ let name = `webNavigation.${eventName}`;
+ let register = (callback, urlFilters) => {
+ // Don't create a MatchURLFilters instance if the listener does not include any filter.
+ let filters = urlFilters ?
+ new MatchURLFilters(urlFilters.url) : null;
+
+ let listener = data => {
+ if (!data.browser) {
+ return;
+ }
+
+ let data2 = {
+ url: data.url,
+ timeStamp: Date.now(),
+ frameId: ExtensionManagement.getFrameId(data.windowId),
+ parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId),
+ };
+
+ if (eventName == "onErrorOccurred") {
+ data2.error = data.error;
+ }
+
+ // Fills in tabId typically.
+ extensions.emit("fill-browser-data", data.browser, data2);
+ if (data2.tabId < 0) {
+ return;
+ }
+
+ fillTransitionProperties(eventName, data, data2);
+
+ context.runSafe(callback, data2);
+ };
+
+ WebNavigation[eventName].addListener(listener, filters);
+ return () => {
+ WebNavigation[eventName].removeListener(listener);
+ };
+ };
+
+ return SingletonEventManager.call(this, context, name, register);
+}
+
+WebNavigationEventManager.prototype = Object.create(SingletonEventManager.prototype);
+
+function convertGetFrameResult(tabId, data) {
+ return {
+ errorOccurred: data.errorOccurred,
+ url: data.url,
+ tabId,
+ frameId: ExtensionManagement.getFrameId(data.windowId),
+ parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId),
+ };
+}
+
+extensions.registerSchemaAPI("webNavigation", "addon_parent", context => {
+ return {
+ webNavigation: {
+ onTabReplaced: ignoreEvent(context, "webNavigation.onTabReplaced"),
+ onBeforeNavigate: new WebNavigationEventManager(context, "onBeforeNavigate").api(),
+ onCommitted: new WebNavigationEventManager(context, "onCommitted").api(),
+ onDOMContentLoaded: new WebNavigationEventManager(context, "onDOMContentLoaded").api(),
+ onCompleted: new WebNavigationEventManager(context, "onCompleted").api(),
+ onErrorOccurred: new WebNavigationEventManager(context, "onErrorOccurred").api(),
+ onReferenceFragmentUpdated: new WebNavigationEventManager(context, "onReferenceFragmentUpdated").api(),
+ onHistoryStateUpdated: new WebNavigationEventManager(context, "onHistoryStateUpdated").api(),
+ onCreatedNavigationTarget: ignoreEvent(context, "webNavigation.onCreatedNavigationTarget"),
+ getAllFrames(details) {
+ let tab = TabManager.getTab(details.tabId, context);
+
+ let {innerWindowID, messageManager} = tab.linkedBrowser;
+ let recipient = {innerWindowID};
+
+ return context.sendMessage(messageManager, "WebNavigation:GetAllFrames", {}, {recipient})
+ .then((results) => results.map(convertGetFrameResult.bind(null, details.tabId)));
+ },
+ getFrame(details) {
+ let tab = TabManager.getTab(details.tabId, context);
+
+ let recipient = {
+ innerWindowID: tab.linkedBrowser.innerWindowID,
+ };
+
+ let mm = tab.linkedBrowser.messageManager;
+ return context.sendMessage(mm, "WebNavigation:GetFrame", {options: details}, {recipient})
+ .then((result) => {
+ return result ?
+ convertGetFrameResult(details.tabId, result) :
+ Promise.reject({message: `No frame found with frameId: ${details.frameId}`});
+ });
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/ext-webRequest.js b/toolkit/components/webextensions/ext-webRequest.js
new file mode 100644
index 000000000..f92330131
--- /dev/null
+++ b/toolkit/components/webextensions/ext-webRequest.js
@@ -0,0 +1,115 @@
+"use strict";
+
+var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern",
+ "resource://gre/modules/MatchPattern.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "WebRequest",
+ "resource://gre/modules/WebRequest.jsm");
+
+Cu.import("resource://gre/modules/ExtensionManagement.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+var {
+ SingletonEventManager,
+} = ExtensionUtils;
+
+// EventManager-like class specifically for WebRequest. Inherits from
+// SingletonEventManager. Takes care of converting |details| parameter
+// when invoking listeners.
+function WebRequestEventManager(context, eventName) {
+ let name = `webRequest.${eventName}`;
+ let register = (callback, filter, info) => {
+ let listener = data => {
+ // Prevent listening in on requests originating from system principal to
+ // prevent tinkering with OCSP, app and addon updates, etc.
+ if (data.isSystemPrincipal) {
+ return;
+ }
+
+ let data2 = {
+ requestId: data.requestId,
+ url: data.url,
+ originUrl: data.originUrl,
+ method: data.method,
+ type: data.type,
+ timeStamp: Date.now(),
+ frameId: data.type == "main_frame" ? 0 : ExtensionManagement.getFrameId(data.windowId),
+ parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId),
+ };
+
+ const maybeCached = ["onResponseStarted", "onBeforeRedirect", "onCompleted", "onErrorOccurred"];
+ if (maybeCached.includes(eventName)) {
+ data2.fromCache = !!data.fromCache;
+ }
+
+ if ("ip" in data) {
+ data2.ip = data.ip;
+ }
+
+ extensions.emit("fill-browser-data", data.browser, data2);
+
+ let optional = ["requestHeaders", "responseHeaders", "statusCode", "statusLine", "error", "redirectUrl",
+ "requestBody"];
+ for (let opt of optional) {
+ if (opt in data) {
+ data2[opt] = data[opt];
+ }
+ }
+
+ return context.runSafe(callback, data2);
+ };
+
+ let filter2 = {};
+ filter2.urls = new MatchPattern(filter.urls);
+ if (filter.types) {
+ filter2.types = filter.types;
+ }
+ if (filter.tabId) {
+ filter2.tabId = filter.tabId;
+ }
+ if (filter.windowId) {
+ filter2.windowId = filter.windowId;
+ }
+
+ let info2 = [];
+ if (info) {
+ for (let desc of info) {
+ if (desc == "blocking" && !context.extension.hasPermission("webRequestBlocking")) {
+ Cu.reportError("Using webRequest.addListener with the blocking option " +
+ "requires the 'webRequestBlocking' permission.");
+ } else {
+ info2.push(desc);
+ }
+ }
+ }
+
+ WebRequest[eventName].addListener(listener, filter2, info2);
+ return () => {
+ WebRequest[eventName].removeListener(listener);
+ };
+ };
+
+ return SingletonEventManager.call(this, context, name, register);
+}
+
+WebRequestEventManager.prototype = Object.create(SingletonEventManager.prototype);
+
+extensions.registerSchemaAPI("webRequest", "addon_parent", context => {
+ return {
+ webRequest: {
+ onBeforeRequest: new WebRequestEventManager(context, "onBeforeRequest").api(),
+ onBeforeSendHeaders: new WebRequestEventManager(context, "onBeforeSendHeaders").api(),
+ onSendHeaders: new WebRequestEventManager(context, "onSendHeaders").api(),
+ onHeadersReceived: new WebRequestEventManager(context, "onHeadersReceived").api(),
+ onBeforeRedirect: new WebRequestEventManager(context, "onBeforeRedirect").api(),
+ onResponseStarted: new WebRequestEventManager(context, "onResponseStarted").api(),
+ onErrorOccurred: new WebRequestEventManager(context, "onErrorOccurred").api(),
+ onCompleted: new WebRequestEventManager(context, "onCompleted").api(),
+ handlerBehaviorChanged: function() {
+ // TODO: Flush all caches.
+ },
+ },
+ };
+});
diff --git a/toolkit/components/webextensions/extensions-toolkit.manifest b/toolkit/components/webextensions/extensions-toolkit.manifest
new file mode 100644
index 000000000..4ec65a984
--- /dev/null
+++ b/toolkit/components/webextensions/extensions-toolkit.manifest
@@ -0,0 +1,49 @@
+# scripts
+category webextension-scripts alarms chrome://extensions/content/ext-alarms.js
+category webextension-scripts backgroundPage chrome://extensions/content/ext-backgroundPage.js
+category webextension-scripts cookies chrome://extensions/content/ext-cookies.js
+category webextension-scripts downloads chrome://extensions/content/ext-downloads.js
+category webextension-scripts management chrome://extensions/content/ext-management.js
+category webextension-scripts notifications chrome://extensions/content/ext-notifications.js
+category webextension-scripts i18n chrome://extensions/content/ext-i18n.js
+category webextension-scripts idle chrome://extensions/content/ext-idle.js
+category webextension-scripts webRequest chrome://extensions/content/ext-webRequest.js
+category webextension-scripts webNavigation chrome://extensions/content/ext-webNavigation.js
+category webextension-scripts runtime chrome://extensions/content/ext-runtime.js
+category webextension-scripts extension chrome://extensions/content/ext-extension.js
+category webextension-scripts storage chrome://extensions/content/ext-storage.js
+category webextension-scripts topSites chrome://extensions/content/ext-topSites.js
+
+# scripts specific for content process.
+category webextension-scripts-content extension chrome://extensions/content/ext-c-extension.js
+category webextension-scripts-content i18n chrome://extensions/content/ext-i18n.js
+category webextension-scripts-content runtime chrome://extensions/content/ext-c-runtime.js
+category webextension-scripts-content test chrome://extensions/content/ext-c-test.js
+category webextension-scripts-content storage chrome://extensions/content/ext-c-storage.js
+
+# scripts that must run in the same process as addon code.
+category webextension-scripts-addon backgroundPage chrome://extensions/content/ext-c-backgroundPage.js
+category webextension-scripts-addon extension chrome://extensions/content/ext-c-extension.js
+category webextension-scripts-addon i18n chrome://extensions/content/ext-i18n.js
+category webextension-scripts-addon runtime chrome://extensions/content/ext-c-runtime.js
+category webextension-scripts-addon test chrome://extensions/content/ext-c-test.js
+category webextension-scripts-addon storage chrome://extensions/content/ext-c-storage.js
+
+# schemas
+category webextension-schemas alarms chrome://extensions/content/schemas/alarms.json
+category webextension-schemas cookies chrome://extensions/content/schemas/cookies.json
+category webextension-schemas downloads chrome://extensions/content/schemas/downloads.json
+category webextension-schemas events chrome://extensions/content/schemas/events.json
+category webextension-schemas extension chrome://extensions/content/schemas/extension.json
+category webextension-schemas extension_types chrome://extensions/content/schemas/extension_types.json
+category webextension-schemas i18n chrome://extensions/content/schemas/i18n.json
+category webextension-schemas idle chrome://extensions/content/schemas/idle.json
+category webextension-schemas management chrome://extensions/content/schemas/management.json
+category webextension-schemas native_host_manifest chrome://extensions/content/schemas/native_host_manifest.json
+category webextension-schemas notifications chrome://extensions/content/schemas/notifications.json
+category webextension-schemas runtime chrome://extensions/content/schemas/runtime.json
+category webextension-schemas storage chrome://extensions/content/schemas/storage.json
+category webextension-schemas test chrome://extensions/content/schemas/test.json
+category webextension-schemas top_sites chrome://extensions/content/schemas/top_sites.json
+category webextension-schemas web_navigation chrome://extensions/content/schemas/web_navigation.json
+category webextension-schemas web_request chrome://extensions/content/schemas/web_request.json
diff --git a/toolkit/components/webextensions/jar.mn b/toolkit/components/webextensions/jar.mn
new file mode 100644
index 000000000..6d343e1b7
--- /dev/null
+++ b/toolkit/components/webextensions/jar.mn
@@ -0,0 +1,26 @@
+# 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/.
+
+toolkit.jar:
+% content extensions %content/extensions/
+ content/extensions/ext-alarms.js
+ content/extensions/ext-backgroundPage.js
+ content/extensions/ext-browser-content.js
+ content/extensions/ext-cookies.js
+ content/extensions/ext-downloads.js
+ content/extensions/ext-management.js
+ content/extensions/ext-notifications.js
+ content/extensions/ext-i18n.js
+ content/extensions/ext-idle.js
+ content/extensions/ext-webRequest.js
+ content/extensions/ext-webNavigation.js
+ content/extensions/ext-runtime.js
+ content/extensions/ext-extension.js
+ content/extensions/ext-storage.js
+ content/extensions/ext-topSites.js
+ content/extensions/ext-c-backgroundPage.js
+ content/extensions/ext-c-extension.js
+ content/extensions/ext-c-runtime.js
+ content/extensions/ext-c-storage.js
+ content/extensions/ext-c-test.js
diff --git a/toolkit/components/webextensions/moz.build b/toolkit/components/webextensions/moz.build
new file mode 100644
index 000000000..f32f526f9
--- /dev/null
+++ b/toolkit/components/webextensions/moz.build
@@ -0,0 +1,41 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+EXTRA_JS_MODULES += [
+ 'Extension.jsm',
+ 'ExtensionAPI.jsm',
+ 'ExtensionChild.jsm',
+ 'ExtensionCommon.jsm',
+ 'ExtensionContent.jsm',
+ 'ExtensionManagement.jsm',
+ 'ExtensionParent.jsm',
+ 'ExtensionStorage.jsm',
+ 'ExtensionUtils.jsm',
+ 'LegacyExtensionsUtils.jsm',
+ 'MessageChannel.jsm',
+ 'NativeMessaging.jsm',
+ 'Schemas.jsm',
+]
+
+EXTRA_COMPONENTS += [
+ 'extensions-toolkit.manifest',
+]
+
+TESTING_JS_MODULES += [
+ 'ExtensionTestCommon.jsm',
+ 'ExtensionXPCShellUtils.jsm',
+]
+
+DIRS += ['schemas']
+
+JAR_MANIFESTS += ['jar.mn']
+
+MOCHITEST_MANIFESTS += ['test/mochitest/mochitest.ini']
+MOCHITEST_CHROME_MANIFESTS += ['test/mochitest/chrome.ini']
+XPCSHELL_TESTS_MANIFESTS += [
+ 'test/xpcshell/native_messaging.ini',
+ 'test/xpcshell/xpcshell.ini',
+]
diff --git a/toolkit/components/webextensions/schemas/LICENSE b/toolkit/components/webextensions/schemas/LICENSE
new file mode 100644
index 000000000..9314092fd
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/LICENSE
@@ -0,0 +1,27 @@
+// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/toolkit/components/webextensions/schemas/alarms.json b/toolkit/components/webextensions/schemas/alarms.json
new file mode 100644
index 000000000..2a72a2842
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/alarms.json
@@ -0,0 +1,145 @@
+// 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.
+
+[
+ {
+ "namespace": "alarms",
+ "permissions": ["alarms"],
+ "types": [
+ {
+ "id": "Alarm",
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Name of this alarm."
+ },
+ "scheduledTime": {
+ "type": "number",
+ "description": "Time when the alarm is scheduled to fire, in milliseconds past the epoch."
+ },
+ "periodInMinutes": {
+ "type": "number",
+ "optional": true,
+ "description": "When present, signals that the alarm triggers periodically after so many minutes."
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "create",
+ "type": "function",
+ "description": "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.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "name",
+ "optional": true,
+ "description": "Optional name to identify this alarm. Defaults to the empty string."
+ },
+ {
+ "type": "object",
+ "name": "alarmInfo",
+ "description": "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.",
+ "properties": {
+ "when": {"type": "number", "optional": true,
+ "description": "Time when the alarm is scheduled to first fire, in milliseconds past the epoch."},
+ "delayInMinutes": {"type": "number", "optional": true,
+ "description": "Number of minutes from the current time after which the alarm should first fire."},
+ "periodInMinutes": {"type": "number", "optional": true,
+ "description": "Number of minutes after which the alarm should recur repeatedly."}
+ }
+ }
+ ]
+ },
+ {
+ "name": "get",
+ "type": "function",
+ "description": "Retrieves details about the specified alarm.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "name",
+ "optional": true,
+ "description": "The name of the alarm to get. Defaults to the empty string."
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ { "name": "alarm", "$ref": "Alarm" }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getAll",
+ "type": "function",
+ "description": "Gets an array of all the alarms.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ { "name": "alarms", "type": "array", "items": { "$ref": "Alarm" } }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "clear",
+ "type": "function",
+ "description": "Clears the alarm with the given name.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "name",
+ "optional": true,
+ "description": "The name of the alarm to clear. Defaults to the empty string."
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ { "name": "wasCleared", "type": "boolean", "description": "Whether an alarm of the given name was found to clear." }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "clearAll",
+ "type": "function",
+ "description": "Clears all alarms.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ { "name": "wasCleared", "type": "boolean", "description": "Whether any alarm was found to clear." }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onAlarm",
+ "type": "function",
+ "description": "Fired when an alarm has expired. Useful for transient background pages.",
+ "parameters": [
+ {
+ "name": "name",
+ "$ref": "Alarm",
+ "description": "The alarm that has expired."
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/cookies.json b/toolkit/components/webextensions/schemas/cookies.json
new file mode 100644
index 000000000..a7de6eb42
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/cookies.json
@@ -0,0 +1,224 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "cookies"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "cookies",
+ "description": "Use the <code>browser.cookies</code> API to query and modify cookies, and to be notified when they change.",
+ "permissions": ["cookies"],
+ "types": [
+ {
+ "id": "Cookie",
+ "type": "object",
+ "description": "Represents information about an HTTP cookie.",
+ "properties": {
+ "name": {"type": "string", "description": "The name of the cookie."},
+ "value": {"type": "string", "description": "The value of the cookie."},
+ "domain": {"type": "string", "description": "The domain of the cookie (e.g. \"www.google.com\", \"example.com\")."},
+ "hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."},
+ "path": {"type": "string", "description": "The path of the cookie."},
+ "secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."},
+ "httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."},
+ "session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."},
+ "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."},
+ "storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."}
+ }
+ },
+ {
+ "id": "CookieStore",
+ "type": "object",
+ "description": "Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window.",
+ "properties": {
+ "id": {"type": "string", "description": "The unique identifier for the cookie store."},
+ "tabIds": {"type": "array", "items": {"type": "integer"}, "description": "Identifiers of all the browser tabs that share this cookie store."}
+ }
+ },
+ {
+ "id": "OnChangedCause",
+ "type": "string",
+ "enum": ["evicted", "expired", "explicit", "expired_overwrite", "overwrite"],
+ "description": "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."
+ }
+ ],
+ "functions": [
+ {
+ "name": "get",
+ "type": "function",
+ "description": "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.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Details to identify the cookie being retrieved.",
+ "properties": {
+ "url": {"type": "string", "description": "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."},
+ "name": {"type": "string", "description": "The name of the cookie to retrieve."},
+ "storeId": {"type": "string", "optional": true, "description": "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."}
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie. This parameter is null if no such cookie was found."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getAll",
+ "type": "function",
+ "description": "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.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Information to filter the cookies being retrieved.",
+ "properties": {
+ "url": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those that would match the given URL."},
+ "name": {"type": "string", "optional": true, "description": "Filters the cookies by name."},
+ "domain": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."},
+ "path": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose path exactly matches this string."},
+ "secure": {"type": "boolean", "optional": true, "description": "Filters the cookies by their Secure property."},
+ "session": {"type": "boolean", "optional": true, "description": "Filters out session vs. persistent cookies."},
+ "storeId": {"type": "string", "optional": true, "description": "The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used."}
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "cookies", "type": "array", "items": {"$ref": "Cookie"}, "description": "All the existing, unexpired cookies that match the given cookie info."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "set",
+ "type": "function",
+ "description": "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Details about the cookie being set.",
+ "properties": {
+ "url": {"type": "string", "description": "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."},
+ "name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."},
+ "value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."},
+ "domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."},
+ "path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."},
+ "secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."},
+ "httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."},
+ "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."},
+ "storeId": {"type": "string", "optional": true, "description": "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."}
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set. If setting failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "remove",
+ "type": "function",
+ "description": "Deletes a cookie by name.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Information to identify the cookie to remove.",
+ "properties": {
+ "url": {"type": "string", "description": "The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."},
+ "name": {"type": "string", "description": "The name of the cookie to remove."},
+ "storeId": {"type": "string", "optional": true, "description": "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."}
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "details",
+ "type": "object",
+ "description": "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.",
+ "optional": true,
+ "properties": {
+ "url": {"type": "string", "description": "The URL associated with the cookie that's been removed."},
+ "name": {"type": "string", "description": "The name of the cookie that's been removed."},
+ "storeId": {"type": "string", "description": "The ID of the cookie store from which the cookie was removed."}
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getAllCookieStores",
+ "type": "function",
+ "description": "Lists all existing cookie stores.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "cookieStores", "type": "array", "items": {"$ref": "CookieStore"}, "description": "All the existing cookie stores."
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onChanged",
+ "type": "function",
+ "description": "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\".",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "changeInfo",
+ "properties": {
+ "removed": {"type": "boolean", "description": "True if a cookie was removed."},
+ "cookie": {"$ref": "Cookie", "description": "Information about the cookie that was set or removed."},
+ "cause": {"$ref": "OnChangedCause", "description": "The underlying reason behind the cookie's change."}
+ }
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/downloads.json b/toolkit/components/webextensions/schemas/downloads.json
new file mode 100644
index 000000000..dcd43e4e1
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/downloads.json
@@ -0,0 +1,793 @@
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "downloads",
+ "downloads.open",
+ "downloads.shelf"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "downloads",
+ "permissions": ["downloads"],
+ "types": [
+ {
+ "id": "FilenameConflictAction",
+ "type": "string",
+ "enum": [
+ "uniquify",
+ "overwrite",
+ "prompt"
+ ]
+ },
+ {
+ "id": "InterruptReason",
+ "type": "string",
+ "enum": [
+ "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"
+ ]
+ },
+ {
+ "id": "DangerType",
+ "type": "string",
+ "enum": [
+ "file",
+ "url",
+ "content",
+ "uncommon",
+ "host",
+ "unwanted",
+ "safe",
+ "accepted"
+ ],
+ "description": "<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."
+ },
+ {
+ "id": "State",
+ "type": "string",
+ "enum": [
+ "in_progress",
+ "interrupted",
+ "complete"
+ ],
+ "description": "<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."
+ },
+ {
+ "id": "DownloadItem",
+ "type": "object",
+ "properties": {
+ "id": {
+ "description": "An identifier that is persistent across browser sessions.",
+ "type": "integer"
+ },
+ "url": {
+ "description": "Absolute URL.",
+ "type": "string"
+ },
+ "referrer": {
+ "type": "string"
+ },
+ "filename": {
+ "description": "Absolute local path.",
+ "type": "string"
+ },
+ "incognito": {
+ "description": "False if this download is recorded in the history, true if it is not recorded.",
+ "type": "boolean"
+ },
+ "danger": {
+ "$ref": "DangerType",
+ "description": "Indication of whether this download is thought to be safe or known to be suspicious."
+ },
+ "mime": {
+ "description": "The file's MIME type.",
+ "type": "string"
+ },
+ "startTime": {
+ "description": "Number of milliseconds between the unix epoch and when this download began.",
+ "type": "string"
+ },
+ "endTime": {
+ "description": "Number of milliseconds between the unix epoch and when this download ended.",
+ "optional": true,
+ "type": "string"
+ },
+ "estimatedEndTime": {
+ "type": "string",
+ "optional": true
+ },
+ "state": {
+ "$ref": "State",
+ "description": "Indicates whether the download is progressing, interrupted, or complete."
+ },
+ "paused": {
+ "description": "True if the download has stopped reading data from the host, but kept the connection open.",
+ "type": "boolean"
+ },
+ "canResume": {
+ "type": "boolean"
+ },
+ "error": {
+ "description": "Number indicating why a download was interrupted.",
+ "optional": true,
+ "$ref": "InterruptReason"
+ },
+ "bytesReceived": {
+ "description": "Number of bytes received so far from the host, without considering file compression.",
+ "type": "number"
+ },
+ "totalBytes": {
+ "description": "Number of bytes in the whole file, without considering file compression, or -1 if unknown.",
+ "type": "number"
+ },
+ "fileSize": {
+ "description": "Number of bytes in the whole file post-decompression, or -1 if unknown.",
+ "type": "number"
+ },
+ "exists": {
+ "type": "boolean"
+ },
+ "byExtensionId": {
+ "type": "string",
+ "optional": true
+ },
+ "byExtensionName": {
+ "type": "string",
+ "optional": true
+ }
+ }
+ },
+ {
+ "id": "StringDelta",
+ "type": "object",
+ "properties": {
+ "current": {
+ "optional": true,
+ "type": "string"
+ },
+ "previous": {
+ "optional": true,
+ "type": "string"
+ }
+ }
+ },
+ {
+ "id": "DoubleDelta",
+ "type": "object",
+ "properties": {
+ "current": {
+ "optional": true,
+ "type": "number"
+ },
+ "previous": {
+ "optional": true,
+ "type": "number"
+ }
+ }
+ },
+ {
+ "id": "BooleanDelta",
+ "type": "object",
+ "properties": {
+ "current": {
+ "optional": true,
+ "type": "boolean"
+ },
+ "previous": {
+ "optional": true,
+ "type": "boolean"
+ }
+ }
+ },
+ {
+ "id": "DownloadTime",
+ "description": "A time specified as a Date object, a number or string representing milliseconds since the epoch, or an ISO 8601 string",
+ "choices": [
+ {
+ "type": "string",
+ "pattern": "^[1-9]\\d*$"
+ },
+ {
+ "$ref": "extensionTypes.Date"
+ }
+ ]
+ },
+ {
+ "id": "DownloadQuery",
+ "description": "Parameters that combine to specify a predicate that can be used to select a set of downloads. Used for example in search() and erase()",
+ "type": "object",
+ "properties": {
+ "query": {
+ "description": "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": true,
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "startedBefore": {
+ "description": "Limits results to downloads that started before the given ms since the epoch.",
+ "optional": true,
+ "$ref": "DownloadTime"
+ },
+ "startedAfter": {
+ "description": "Limits results to downloads that started after the given ms since the epoch.",
+ "optional": true,
+ "$ref": "DownloadTime"
+ },
+ "endedBefore": {
+ "description": "Limits results to downloads that ended before the given ms since the epoch.",
+ "optional": true,
+ "$ref": "DownloadTime"
+ },
+ "endedAfter": {
+ "description": "Limits results to downloads that ended after the given ms since the epoch.",
+ "optional": true,
+ "$ref": "DownloadTime"
+ },
+ "totalBytesGreater": {
+ "description": "Limits results to downloads whose totalBytes is greater than the given integer.",
+ "optional": true,
+ "type": "number"
+ },
+ "totalBytesLess": {
+ "description": "Limits results to downloads whose totalBytes is less than the given integer.",
+ "optional": true,
+ "type": "number"
+ },
+ "filenameRegex": {
+ "description": "Limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>filename</code> matches the given regular expression.",
+ "optional": true,
+ "type": "string"
+ },
+ "urlRegex": {
+ "description": "Limits results to <a href='#type-DownloadItem'>DownloadItems</a> whose <code>url</code> matches the given regular expression.",
+ "optional": true,
+ "type": "string"
+ },
+ "limit": {
+ "description": "Setting this integer limits the number of results. Otherwise, all matching <a href='#type-DownloadItem'>DownloadItems</a> will be returned.",
+ "optional": true,
+ "type": "integer"
+ },
+ "orderBy": {
+ "description": "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": true,
+ "type": "array",
+ "items": { "type": "string" }
+ },
+ "id": {
+ "type": "integer",
+ "optional": true
+ },
+ "url": {
+ "description": "Absolute URL.",
+ "optional": true,
+ "type": "string"
+ },
+ "filename": {
+ "description": "Absolute local path.",
+ "optional": true,
+ "type": "string"
+ },
+ "danger": {
+ "$ref": "DangerType",
+ "description": "Indication of whether this download is thought to be safe or known to be suspicious.",
+ "optional": true
+ },
+ "mime": {
+ "description": "The file's MIME type.",
+ "optional": true,
+ "type": "string"
+ },
+ "startTime": {
+ "optional": true,
+ "type": "string"
+ },
+ "endTime": {
+ "optional": true,
+ "type": "string"
+ },
+ "state": {
+ "$ref": "State",
+ "description": "Indicates whether the download is progressing, interrupted, or complete.",
+ "optional": true
+ },
+ "paused": {
+ "description": "True if the download has stopped reading data from the host, but kept the connection open.",
+ "optional": true,
+ "type": "boolean"
+ },
+ "error": {
+ "description": "Why a download was interrupted.",
+ "optional": true,
+ "$ref": "InterruptReason"
+ },
+ "bytesReceived": {
+ "description": "Number of bytes received so far from the host, without considering file compression.",
+ "optional": true,
+ "type": "number"
+ },
+ "totalBytes": {
+ "description": "Number of bytes in the whole file, without considering file compression, or -1 if unknown.",
+ "optional": true,
+ "type": "number"
+ },
+ "fileSize": {
+ "description": "Number of bytes in the whole file post-decompression, or -1 if unknown.",
+ "optional": true,
+ "type": "number"
+ },
+ "exists": {
+ "type": "boolean",
+ "optional": true
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "download",
+ "type": "function",
+ "async": "callback",
+ "description": "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.",
+ "parameters": [
+ {
+ "description": "What to download and how.",
+ "name": "options",
+ "type": "object",
+ "properties": {
+ "url": {
+ "description": "The URL to download.",
+ "type": "string",
+ "format": "url"
+ },
+ "filename": {
+ "description": "A file path relative to the Downloads directory to contain the downloaded file.",
+ "optional": true,
+ "type": "string"
+ },
+ "conflictAction": {
+ "$ref": "FilenameConflictAction",
+ "optional": true
+ },
+ "saveAs": {
+ "description": "Use a file-chooser to allow the user to select a filename.",
+ "optional": true,
+ "type": "boolean"
+ },
+ "method": {
+ "description": "The HTTP method to use if the URL uses the HTTP[S] protocol.",
+ "enum": [
+ "GET",
+ "POST"
+ ],
+ "optional": true,
+ "type": "string"
+ },
+ "headers": {
+ "optional": true,
+ "type": "array",
+ "description": "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.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "description": "Name of the HTTP header.",
+ "type": "string"
+ },
+ "value": {
+ "description": "Value of the HTTP header.",
+ "type": "string"
+ }
+ }
+ }
+ },
+ "body": {
+ "description": "Post body.",
+ "optional": true,
+ "type": "string"
+ }
+ }
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "search",
+ "type": "function",
+ "async": "callback",
+ "description": "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.",
+ "parameters": [
+ {
+ "name": "query",
+ "$ref": "DownloadQuery"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "items": {
+ "$ref": "DownloadItem"
+ },
+ "name": "results",
+ "type": "array"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "pause",
+ "type": "function",
+ "async": "callback",
+ "description": "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.",
+ "parameters": [
+ {
+ "description": "The id of the download to pause.",
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "optional": true,
+ "parameters": [],
+ "type": "function"
+ }
+ ]
+ },
+ {
+ "name": "resume",
+ "type": "function",
+ "async": "callback",
+ "description": "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.",
+ "parameters": [
+ {
+ "description": "The id of the download to resume.",
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "optional": true,
+ "parameters": [],
+ "type": "function"
+ }
+ ]
+ },
+ {
+ "name": "cancel",
+ "type": "function",
+ "async": "callback",
+ "description": "Cancel a download. When <code>callback</code> is run, the download is cancelled, completed, interrupted or doesn't exist anymore.",
+ "parameters": [
+ {
+ "description": "The id of the download to cancel.",
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "optional": true,
+ "parameters": [],
+ "type": "function"
+ }
+ ]
+ },
+ {
+ "name": "getFileIcon",
+ "type": "function",
+ "async": "callback",
+ "description": "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.",
+ "parameters": [
+ {
+ "description": "The identifier for the download.",
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "options",
+ "optional": true,
+ "properties": {
+ "size": {
+ "description": "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": true,
+ "minimum": 1,
+ "maximum": 127,
+ "type": "integer"
+ }
+ },
+ "type": "object"
+ },
+ {
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "iconURL",
+ "optional": true,
+ "type": "string"
+ }
+ ],
+ "type": "function"
+ }
+ ]
+ },
+ {
+ "name": "open",
+ "type": "function",
+ "async": "callback",
+ "description": "Open the downloaded file.",
+ "permissions": ["downloads.open"],
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": []
+ }
+ ]
+ },
+ {
+ "name": "show",
+ "type": "function",
+ "description": "Show the downloaded file in its folder in a file manager.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "success",
+ "type": "boolean"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "showDefaultFolder",
+ "type": "function",
+ "parameters": []
+ },
+ {
+ "name": "erase",
+ "type": "function",
+ "async": "callback",
+ "description": "Erase matching <a href='#type-DownloadItem'>DownloadItems</a> from history",
+ "parameters": [
+ {
+ "name": "query",
+ "$ref": "DownloadQuery"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [
+ {
+ "items": {
+ "type": "integer"
+ },
+ "name": "erasedIds",
+ "type": "array"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "removeFile",
+ "async": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [ ]
+ }
+ ]
+ },
+ {
+ "description": "Prompt the user to either accept or cancel a dangerous download. <code>acceptDanger()</code> does not automatically accept dangerous downloads.",
+ "name": "acceptDanger",
+ "unsupported": true,
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [ ]
+ }
+ ],
+ "type": "function"
+ },
+ {
+ "description": "Initiate dragging the file to another application.",
+ "name": "drag",
+ "unsupported": true,
+ "parameters": [
+ {
+ "name": "downloadId",
+ "type": "integer"
+ }
+ ],
+ "type": "function"
+ },
+ {
+ "name": "setShelfEnabled",
+ "type": "function",
+ "unsupported": true,
+ "parameters": [
+ {
+ "name": "enabled",
+ "type": "boolean"
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "description": "This event fires with the <a href='#type-DownloadItem'>DownloadItem</a> object when a download begins.",
+ "name": "onCreated",
+ "parameters": [
+ {
+ "$ref": "DownloadItem",
+ "name": "downloadItem"
+ }
+ ],
+ "type": "function"
+ },
+ {
+ "description": "Fires with the <code>downloadId</code> when a download is erased from history.",
+ "name": "onErased",
+ "parameters": [
+ {
+ "name": "downloadId",
+ "description": "The <code>id</code> of the <a href='#type-DownloadItem'>DownloadItem</a> that was erased.",
+ "type": "integer"
+ }
+ ],
+ "type": "function"
+ },
+ {
+ "name": "onChanged",
+ "description": "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.",
+ "parameters": [
+ {
+ "name": "downloadDelta",
+ "type": "object",
+ "properties": {
+ "id": {
+ "description": "The <code>id</code> of the <a href='#type-DownloadItem'>DownloadItem</a> that changed.",
+ "type": "integer"
+ },
+ "url": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>url</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "filename": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>filename</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "danger": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>danger</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "mime": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>mime</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "startTime": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>startTime</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "endTime": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>endTime</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "state": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>state</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "canResume": {
+ "optional": true,
+ "$ref": "BooleanDelta"
+ },
+ "paused": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>paused</code>.",
+ "optional": true,
+ "$ref": "BooleanDelta"
+ },
+ "error": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>error</code>.",
+ "optional": true,
+ "$ref": "StringDelta"
+ },
+ "totalBytes": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>totalBytes</code>.",
+ "optional": true,
+ "$ref": "DoubleDelta"
+ },
+ "fileSize": {
+ "description": "Describes a change in a <a href='#type-DownloadItem'>DownloadItem</a>'s <code>fileSize</code>.",
+ "optional": true,
+ "$ref": "DoubleDelta"
+ },
+ "exists": {
+ "optional": true,
+ "$ref": "BooleanDelta"
+ }
+ }
+ }
+ ],
+ "type": "function"
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/events.json b/toolkit/components/webextensions/schemas/events.json
new file mode 100644
index 000000000..ea3cbb5d2
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/events.json
@@ -0,0 +1,322 @@
+// 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.
+
+[
+ {
+ "namespace": "events",
+ "description": "The <code>chrome.events</code> namespace contains common types used by APIs dispatching events to notify you when something interesting happens.",
+ "types": [
+ {
+ "id": "Rule",
+ "type": "object",
+ "description": "Description of a declarative rule for handling events.",
+ "properties": {
+ "id": {
+ "type": "string",
+ "optional": true,
+ "description": "Optional identifier that allows referencing this rule."
+ },
+ "tags": {
+ "type": "array",
+ "items": {"type": "string"},
+ "optional": true,
+ "description": "Tags can be used to annotate rules and perform operations on sets of rules."
+ },
+ "conditions": {
+ "type": "array",
+ "items": {"type": "any"},
+ "description": "List of conditions that can trigger the actions."
+ },
+ "actions": {
+ "type": "array",
+ "items": {"type": "any"},
+ "description": "List of actions that are triggered if one of the condtions is fulfilled."
+ },
+ "priority": {
+ "type": "integer",
+ "optional": true,
+ "description": "Optional priority of this rule. Defaults to 100."
+ }
+ }
+ },
+ {
+ "id": "Event",
+ "type": "object",
+ "description": "An object which allows the addition and removal of listeners for a Chrome event.",
+ "functions": [
+ {
+ "name": "addListener",
+ "type": "function",
+ "description": "Registers an event listener <em>callback</em> to an event.",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Called when an event occurs. The parameters of this function depend on the type of event."
+ }
+ ]
+ },
+ {
+ "name": "removeListener",
+ "type": "function",
+ "description": "Deregisters an event listener <em>callback</em> from an event.",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Listener that shall be unregistered."
+ }
+ ]
+ },
+ {
+ "name": "hasListener",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Listener whose registration status shall be tested."
+ }
+ ],
+ "returns": {
+ "type": "boolean",
+ "description": "True if <em>callback</em> is registered to the event."
+ }
+ },
+ {
+ "name": "hasListeners",
+ "type": "function",
+ "parameters": [],
+ "returns": {
+ "type": "boolean",
+ "description": "True if any event listeners are registered to the event."
+ }
+ },
+ {
+ "name": "addRules",
+ "unsupported": true,
+ "type": "function",
+ "description": "Registers rules to handle events.",
+ "parameters": [
+ {
+ "name": "eventName",
+ "type": "string",
+ "description": "Name of the event this function affects."
+ },
+ {
+ "name": "webViewInstanceId",
+ "type": "integer",
+ "description": "If provided, this is an integer that uniquely identfies the <webview> associated with this function call."
+ },
+ {
+ "name": "rules",
+ "type": "array",
+ "items": {"$ref": "Rule"},
+ "description": "Rules to be registered. These do not replace previously registered rules."
+ },
+ {
+ "name": "callback",
+ "optional": true,
+ "type": "function",
+ "parameters": [
+ {
+ "name": "rules",
+ "type": "array",
+ "items": {"$ref": "Rule"},
+ "description": "Rules that were registered, the optional parameters are filled with values."
+ }
+ ],
+ "description": "Called with registered rules."
+ }
+ ]
+ },
+ {
+ "name": "getRules",
+ "unsupported": true,
+ "type": "function",
+ "description": "Returns currently registered rules.",
+ "parameters": [
+ {
+ "name": "eventName",
+ "type": "string",
+ "description": "Name of the event this function affects."
+ },
+ {
+ "name": "webViewInstanceId",
+ "type": "integer",
+ "description": "If provided, this is an integer that uniquely identfies the <webview> associated with this function call."
+ },
+ {
+ "name": "ruleIdentifiers",
+ "optional": true,
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "If an array is passed, only rules with identifiers contained in this array are returned."
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "rules",
+ "type": "array",
+ "items": {"$ref": "Rule"},
+ "description": "Rules that were registered, the optional parameters are filled with values."
+ }
+ ],
+ "description": "Called with registered rules."
+ }
+ ]
+ },
+ {
+ "name": "removeRules",
+ "unsupported": true,
+ "type": "function",
+ "description": "Unregisters currently registered rules.",
+ "parameters": [
+ {
+ "name": "eventName",
+ "type": "string",
+ "description": "Name of the event this function affects."
+ },
+ {
+ "name": "webViewInstanceId",
+ "type": "integer",
+ "description": "If provided, this is an integer that uniquely identfies the <webview> associated with this function call."
+ },
+ {
+ "name": "ruleIdentifiers",
+ "optional": true,
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "If an array is passed, only rules with identifiers contained in this array are unregistered."
+ },
+ {
+ "name": "callback",
+ "optional": true,
+ "type": "function",
+ "parameters": [],
+ "description": "Called when rules were unregistered."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "UrlFilter",
+ "type": "object",
+ "description": "Filters URLs for various criteria. See <a href='events#filtered'>event filtering</a>. All criteria are case sensitive.",
+ "properties": {
+ "hostContains": {
+ "type": "string",
+ "description": "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": true
+ },
+ "hostEquals": {
+ "type": "string",
+ "description": "Matches if the host name of the URL is equal to a specified string.",
+ "optional": true
+ },
+ "hostPrefix": {
+ "type": "string",
+ "description": "Matches if the host name of the URL starts with a specified string.",
+ "optional": true
+ },
+ "hostSuffix": {
+ "type": "string",
+ "description": "Matches if the host name of the URL ends with a specified string.",
+ "optional": true
+ },
+ "pathContains": {
+ "type": "string",
+ "description": "Matches if the path segment of the URL contains a specified string.",
+ "optional": true
+ },
+ "pathEquals": {
+ "type": "string",
+ "description": "Matches if the path segment of the URL is equal to a specified string.",
+ "optional": true
+ },
+ "pathPrefix": {
+ "type": "string",
+ "description": "Matches if the path segment of the URL starts with a specified string.",
+ "optional": true
+ },
+ "pathSuffix": {
+ "type": "string",
+ "description": "Matches if the path segment of the URL ends with a specified string.",
+ "optional": true
+ },
+ "queryContains": {
+ "type": "string",
+ "description": "Matches if the query segment of the URL contains a specified string.",
+ "optional": true
+ },
+ "queryEquals": {
+ "type": "string",
+ "description": "Matches if the query segment of the URL is equal to a specified string.",
+ "optional": true
+ },
+ "queryPrefix": {
+ "type": "string",
+ "description": "Matches if the query segment of the URL starts with a specified string.",
+ "optional": true
+ },
+ "querySuffix": {
+ "type": "string",
+ "description": "Matches if the query segment of the URL ends with a specified string.",
+ "optional": true
+ },
+ "urlContains": {
+ "type": "string",
+ "description": "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": true
+ },
+ "urlEquals": {
+ "type": "string",
+ "description": "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": true
+ },
+ "urlMatches": {
+ "type": "string",
+ "description": "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": true
+ },
+ "originAndPathMatches": {
+ "type": "string",
+ "description": "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": true
+ },
+ "urlPrefix": {
+ "type": "string",
+ "description": "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": true
+ },
+ "urlSuffix": {
+ "type": "string",
+ "description": "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": true
+ },
+ "schemes": {
+ "type": "array",
+ "description": "Matches if the scheme of the URL is equal to any of the schemes specified in the array.",
+ "optional": true,
+ "items": { "type": "string" }
+ },
+ "ports": {
+ "type": "array",
+ "description": "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": true,
+ "items": {
+ "choices": [
+ {"type": "integer", "description": "A specific port."},
+ {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer"}, "description": "A pair of integers identiying the start and end (both inclusive) of a port range."}
+ ]
+ }
+ }
+ }
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/experiments.json b/toolkit/components/webextensions/schemas/experiments.json
new file mode 100644
index 000000000..c687173a9
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/experiments.json
@@ -0,0 +1,16 @@
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [
+ {
+ "type": "string",
+ "pattern": "^experiments(\\.\\w+)+$"
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/extension.json b/toolkit/components/webextensions/schemas/extension.json
new file mode 100644
index 000000000..5a1b6c935
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/extension.json
@@ -0,0 +1,178 @@
+// 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.
+
+[
+ {
+ "namespace": "extension",
+ "allowedContexts": ["content"],
+ "description": "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].",
+ "properties": {
+ "lastError": {
+ "type": "object",
+ "optional": true,
+ "allowedContexts": ["content"],
+ "description": "Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occured lastError will be <var>undefined</var>.",
+ "properties": {
+ "message": { "type": "string", "description": "Description of the error that has taken place." }
+ },
+ "additionalProperties": {
+ "type": "any"
+ }
+ },
+ "inIncognitoContext": {
+ "type": "boolean",
+ "optional": true,
+ "allowedContexts": ["content"],
+ "description": "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."
+ }
+ },
+ "types": [
+ {
+ "id": "ViewType",
+ "type": "string",
+ "enum": ["tab", "notification", "popup"],
+ "description": "The type of extension view."
+ }
+ ],
+ "functions": [
+ {
+ "name": "getURL",
+ "type": "function",
+ "allowedContexts": ["content"],
+ "description": "Converts a relative path within an extension install directory to a fully-qualified URL.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "path",
+ "description": "A path to a resource within an extension expressed relative to its install directory."
+ }
+ ],
+ "returns": {
+ "type": "string",
+ "description": "The fully-qualified URL to the resource."
+ }
+ },
+ {
+ "name": "getViews",
+ "type": "function",
+ "description": "Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "fetchProperties",
+ "optional": true,
+ "properties": {
+ "type": {
+ "$ref": "ViewType",
+ "optional": true,
+ "description": "The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab', 'notification', 'popup'."
+ },
+ "windowId": {
+ "type": "integer",
+ "optional": true,
+ "description": "The window to restrict the search to. If omitted, returns all views."
+ }
+ }
+ }
+ ],
+ "returns": {
+ "type": "array",
+ "description": "Array of global objects",
+ "items": {
+ "name": "viewGlobals",
+ "type": "object",
+ "isInstanceOf": "Window",
+ "additionalProperties": { "type": "any" }
+ }
+ }
+ },
+ {
+ "name": "getBackgroundPage",
+ "type": "function",
+ "description": "Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page.",
+ "parameters": [],
+ "returns": {
+ "type": "object",
+ "optional": true,
+ "name": "backgroundPageGlobal",
+ "isInstanceOf": "Window",
+ "additionalProperties": { "type": "any" }
+ }
+ },
+ {
+ "name": "isAllowedIncognitoAccess",
+ "type": "function",
+ "description": "Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "isAllowedAccess",
+ "type": "boolean",
+ "description": "True if the extension has access to Incognito mode, false otherwise."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "isAllowedFileSchemeAccess",
+ "type": "function",
+ "description": "Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow access to File URLs' checkbox.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "isAllowedAccess",
+ "type": "boolean",
+ "description": "True if the extension can access the 'file://' scheme, false otherwise."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "setUpdateUrlData",
+ "unsupported": true,
+ "type": "function",
+ "description": "Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions that are hosted in the browser vendor's store.",
+ "parameters": [
+ {"type": "string", "name": "data", "maxLength": 1024}
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onRequest",
+ "unsupported": true,
+ "deprecated": "Please use $(ref:runtime.onMessage).",
+ "type": "function",
+ "description": "Fired when a request is sent from either an extension process or a content script.",
+ "parameters": [
+ {"name": "request", "type": "any", "optional": true, "description": "The request sent by the calling script."},
+ {"name": "sender", "$ref": "runtime.MessageSender" },
+ {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one <code>onRequest</code> listener in the same document, then only one may send a response." }
+ ]
+ },
+ {
+ "name": "onRequestExternal",
+ "unsupported": true,
+ "deprecated": "Please use $(ref:runtime.onMessageExternal).",
+ "type": "function",
+ "description": "Fired when a request is sent from another extension.",
+ "parameters": [
+ {"name": "request", "type": "any", "optional": true, "description": "The request sent by the calling script."},
+ {"name": "sender", "$ref": "runtime.MessageSender" },
+ {"name": "sendResponse", "type": "function", "description": "Function to call when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response." }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/extension_types.json b/toolkit/components/webextensions/schemas/extension_types.json
new file mode 100644
index 000000000..1a88e4e60
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/extension_types.json
@@ -0,0 +1,83 @@
+// 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.
+
+[
+ {
+ "namespace": "extensionTypes",
+ "description": "The <code>browser.extensionTypes</code> API contains type declarations for WebExtensions.",
+ "types": [
+ {
+ "id": "ImageFormat",
+ "type": "string",
+ "enum": ["jpeg", "png"],
+ "description": "The format of an image."
+ },
+ {
+ "id": "ImageDetails",
+ "type": "object",
+ "description": "Details about the format and quality of an image.",
+ "properties": {
+ "format": {
+ "$ref": "ImageFormat",
+ "optional": true,
+ "description": "The format of the resulting image. Default is <code>\"jpeg\"</code>."
+ },
+ "quality": {
+ "type": "integer",
+ "optional": true,
+ "minimum": 0,
+ "maximum": 100,
+ "description": "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."
+ }
+ }
+ },
+ {
+ "id": "RunAt",
+ "type": "string",
+ "enum": ["document_start", "document_end", "document_idle"],
+ "description": "The soonest that the JavaScript or CSS will be injected into the tab."
+ },
+ {
+ "id": "InjectDetails",
+ "type": "object",
+ "description": "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.",
+ "properties": {
+ "code": {"type": "string", "optional": true, "description": "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."},
+ "file": {"type": "string", "optional": true, "description": "JavaScript or CSS file to inject."},
+ "allFrames": {"type": "boolean", "optional": true, "description": "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."},
+ "matchAboutBlank": {"type": "boolean", "optional": true, "description": "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>."},
+ "frameId": {
+ "type": "integer",
+ "minimum": 0,
+ "optional": true,
+ "description": "The ID of the frame to inject the script into. This may not be used in combination with <code>allFrames</code>."
+ },
+ "runAt": {
+ "$ref": "RunAt",
+ "optional": true,
+ "description": "The soonest that the JavaScript or CSS will be injected into the tab. Defaults to \"document_idle\"."
+ }
+ }
+ },
+ {
+ "id": "Date",
+ "choices": [
+ {
+ "type": "string",
+ "format": "date"
+ },
+ {
+ "type": "integer",
+ "minimum": 0
+ },
+ {
+ "type": "object",
+ "isInstanceOf": "Date",
+ "additionalProperties": { "type": "any" }
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/i18n.json b/toolkit/components/webextensions/schemas/i18n.json
new file mode 100644
index 000000000..12dc45dfc
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/i18n.json
@@ -0,0 +1,132 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "WebExtensionManifest",
+ "properties": {
+ "default_locale": {
+ "type": "string",
+ "optional": "true"
+ }
+ }
+ }
+ ]
+ },
+ {
+ "namespace": "i18n",
+ "allowedContexts": ["content"],
+ "defaultContexts": ["content"],
+ "description": "Use the <code>browser.i18n</code> infrastructure to implement internationalization across your whole app or extension.",
+ "types": [
+ {
+ "id": "LanguageCode",
+ "type": "string",
+ "description": "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"
+ }
+ ],
+ "functions": [
+ {
+ "name": "getAcceptLanguages",
+ "type": "function",
+ "description": "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).",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {"name": "languages", "type": "array", "items": {"$ref": "LanguageCode"}, "description": "Array of LanguageCode"}
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getMessage",
+ "type": "function",
+ "description": "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>.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "messageName",
+ "description": "The name of the message, as specified in the <code>$(topic:i18n-messages)[messages.json]</code> file."
+ },
+ {
+ "type": "any",
+ "name": "substitutions",
+ "optional": true,
+ "description": "Substitution strings, if the message requires any."
+ }
+ ],
+ "returns": {
+ "type": "string",
+ "description": "Message localized for current locale."
+ }
+ },
+ {
+ "name": "getUILanguage",
+ "type": "function",
+ "description": "Gets the browser UI language of the browser. This is different from $(ref:i18n.getAcceptLanguages) which returns the preferred user languages.",
+ "parameters": [],
+ "returns": {
+ "type": "string",
+ "description": "The browser UI language code such as en-US or fr-FR."
+ }
+ },
+ {
+ "name": "detectLanguage",
+ "type": "function",
+ "description": "Detects the language of the provided text using CLD.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "text",
+ "description": "User input string to be translated."
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "result",
+ "description": "LanguageDetectionResult object that holds detected langugae reliability and array of DetectedLanguage",
+ "properties": {
+ "isReliable": { "type": "boolean", "description": "CLD detected language reliability" },
+ "languages":
+ {
+ "type": "array",
+ "description": "array of detectedLanguage",
+ "items":
+ {
+ "type": "object",
+ "description": "DetectedLanguage object that holds detected ISO language code and its percentage in the input string",
+ "properties":
+ {
+ "language":
+ {
+ "$ref": "LanguageCode"
+ },
+ "percentage":
+ {
+ "type": "integer",
+ "description": "The percentage of the detected language"
+ }
+ }
+ }
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": []
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/idle.json b/toolkit/components/webextensions/schemas/idle.json
new file mode 100644
index 000000000..e0b3b951e
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/idle.json
@@ -0,0 +1,70 @@
+// 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.
+
+[
+ {
+ "namespace": "idle",
+ "description": "Use the <code>browser.idle</code> API to detect when the machine's idle state changes.",
+ "permissions": ["idle"],
+ "types": [
+ {
+ "id": "IdleState",
+ "type": "string",
+ "enum": ["active", "idle"]
+ }
+ ],
+ "functions": [
+ {
+ "name": "queryState",
+ "type": "function",
+ "description": "Returns \"idle\" if the user has not generated any input for a specified number of seconds, or \"active\" otherwise.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "detectionIntervalInSeconds",
+ "type": "integer",
+ "minimum": 15,
+ "description": "The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected."
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "newState",
+ "$ref": "IdleState"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "setDetectionInterval",
+ "type": "function",
+ "description": "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.",
+ "parameters": [
+ {
+ "name": "intervalInSeconds",
+ "type": "integer",
+ "minimum": 15,
+ "description": "Threshold, in seconds, used to determine when the system is in an idle state."
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onStateChanged",
+ "type": "function",
+ "description": "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.",
+ "parameters": [
+ {
+ "name": "newState",
+ "$ref": "IdleState"
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/jar.mn b/toolkit/components/webextensions/schemas/jar.mn
new file mode 100644
index 000000000..0bdf35b0d
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/jar.mn
@@ -0,0 +1,25 @@
+# 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/.
+
+toolkit.jar:
+% content extensions %content/extensions/
+ content/extensions/schemas/alarms.json
+ content/extensions/schemas/cookies.json
+ content/extensions/schemas/downloads.json
+ content/extensions/schemas/events.json
+ content/extensions/schemas/experiments.json
+ content/extensions/schemas/extension.json
+ content/extensions/schemas/extension_types.json
+ content/extensions/schemas/i18n.json
+ content/extensions/schemas/idle.json
+ content/extensions/schemas/management.json
+ content/extensions/schemas/manifest.json
+ content/extensions/schemas/native_host_manifest.json
+ content/extensions/schemas/notifications.json
+ content/extensions/schemas/runtime.json
+ content/extensions/schemas/storage.json
+ content/extensions/schemas/test.json
+ content/extensions/schemas/top_sites.json
+ content/extensions/schemas/web_navigation.json
+ content/extensions/schemas/web_request.json
diff --git a/toolkit/components/webextensions/schemas/management.json b/toolkit/components/webextensions/schemas/management.json
new file mode 100644
index 000000000..413ff1d0d
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/management.json
@@ -0,0 +1,250 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "management"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace":"management",
+ "description": "The <code>browser.management</code> API provides ways to manage the list of extensions that are installed and running.",
+ "types": [
+ {
+ "id": "IconInfo",
+ "description": "Information about an icon belonging to an extension.",
+ "type": "object",
+ "properties": {
+ "size": {
+ "type": "integer",
+ "description": "A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16."
+ },
+ "url": {
+ "type": "string",
+ "description": "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."
+ }
+ }
+ },
+ {
+ "id": "ExtensionDisabledReason",
+ "description": "A reason the item is disabled.",
+ "type": "string",
+ "enum": ["unknown", "permissions_increase"]
+ },
+ {
+ "id": "ExtensionType",
+ "description": "The type of this extension. Will always be 'extension'.",
+ "type": "string",
+ "enum": ["extension"]
+ },
+ {
+ "id": "ExtensionInstallType",
+ "description": "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": "string",
+ "enum": ["development", "normal", "sideload", "other"]
+ },
+ {
+ "id": "ExtensionInfo",
+ "description": "Information about an installed extension.",
+ "type": "object",
+ "properties": {
+ "id": {
+ "description": "The extension's unique identifier.",
+ "type": "string"
+ },
+ "name": {
+ "description": "The name of this extension.",
+ "type": "string"
+ },
+ "shortName": {
+ "description": "A short version of the name of this extension.",
+ "type": "string"
+ },
+ "description": {
+ "description": "The description of this extension.",
+ "type": "string"
+ },
+ "version": {
+ "description": "The <a href='manifest/version'>version</a> of this extension.",
+ "type": "string"
+ },
+ "versionName": {
+ "description": "The <a href='manifest/version#version_name'>version name</a> of this extension if the manifest specified one.",
+ "type": "string",
+ "optional": true
+ },
+ "mayDisable": {
+ "description": "Whether this extension can be disabled or uninstalled by the user.",
+ "type": "boolean"
+ },
+ "enabled": {
+ "description": "Whether it is currently enabled or disabled.",
+ "type": "boolean"
+ },
+ "disabledReason": {
+ "description": "A reason the item is disabled.",
+ "$ref": "ExtensionDisabledReason",
+ "optional": true
+ },
+ "type": {
+ "description": "The type of this extension. Will always return 'extension'.",
+ "$ref": "ExtensionType"
+ },
+ "homepageUrl": {
+ "description": "The URL of the homepage of this extension.",
+ "type": "string",
+ "optional": true
+ },
+ "updateUrl": {
+ "description": "The update URL of this extension.",
+ "type": "string",
+ "optional": true
+ },
+ "optionsUrl": {
+ "description": "The url for the item's options page, if it has one.",
+ "type": "string"
+ },
+ "icons": {
+ "description": "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.",
+ "type": "array",
+ "optional": true,
+ "items": {
+ "$ref": "IconInfo"
+ }
+ },
+ "permissions": {
+ "description": "Returns a list of API based permissions.",
+ "type": "array",
+ "items" : {
+ "type": "string"
+ }
+ },
+ "hostPermissions": {
+ "description": "Returns a list of host based permissions.",
+ "type": "array",
+ "items" : {
+ "type": "string"
+ }
+ },
+ "installType": {
+ "description": "How the extension was installed.",
+ "$ref": "ExtensionInstallType"
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "getAll",
+ "type": "function",
+ "permissions": ["management"],
+ "unsupported": true,
+ "description": "Returns a list of information about installed extensions.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [
+ {
+ "type": "array",
+ "name": "result",
+ "items": {
+ "$ref": "ExtensionInfo"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "get",
+ "type": "function",
+ "permissions": ["management"],
+ "unsupported": true,
+ "description": "Returns information about the installed extension that has the given ID.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "id",
+ "$ref": "manifest.ExtensionID",
+ "description": "The ID from an item of $(ref:management.ExtensionInfo)."
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "result",
+ "$ref": "ExtensionInfo"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getSelf",
+ "type": "function",
+ "description": "Returns information about the calling extension. Note: This function can be used without requesting the 'management' permission in the manifest.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "result",
+ "$ref": "ExtensionInfo"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "uninstallSelf",
+ "type": "function",
+ "description": "Uninstalls the calling extension. Note: This function can be used without requesting the 'management' permission in the manifest.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "options",
+ "optional": true,
+ "properties": {
+ "showConfirmDialog": {
+ "type": "boolean",
+ "optional": true,
+ "description": "Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false."
+ },
+ "dialogMessage": {
+ "type": "string",
+ "optional": true,
+ "description": "The message to display to a user when being asked to confirm removal of the extension."
+ }
+ }
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "optional": true,
+ "parameters": []
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/manifest.json b/toolkit/components/webextensions/schemas/manifest.json
new file mode 100644
index 000000000..09e6b56fb
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/manifest.json
@@ -0,0 +1,377 @@
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "id": "WebExtensionManifest",
+ "type": "object",
+ "description": "Represents a WebExtension manifest.json file",
+ "properties": {
+ "manifest_version": {
+ "type": "integer",
+ "minimum": 2,
+ "maximum": 2
+ },
+
+ "minimum_chrome_version":{
+ "type": "string",
+ "optional": true
+ },
+
+ "applications": {
+ "type": "object",
+ "optional": true,
+ "properties": {
+ "gecko": {
+ "$ref": "FirefoxSpecificProperties",
+ "optional": true
+ }
+ }
+ },
+
+ "browser_specific_settings": {
+ "type": "object",
+ "optional": true,
+ "properties": {
+ "gecko": {
+ "$ref": "FirefoxSpecificProperties",
+ "optional": true
+ }
+ }
+ },
+
+ "name": {
+ "type": "string",
+ "optional": false,
+ "preprocess": "localize"
+ },
+
+ "short_name": {
+ "type": "string",
+ "optional": true,
+ "preprocess": "localize"
+ },
+
+ "description": {
+ "type": "string",
+ "optional": true,
+ "preprocess": "localize"
+ },
+
+ "author": {
+ "type": "string",
+ "optional": true,
+ "preprocess": "localize",
+ "onError": "warn"
+ },
+
+ "version": {
+ "type": "string",
+ "optional": false
+ },
+
+ "homepage_url": {
+ "type": "string",
+ "format": "url",
+ "optional": true,
+ "preprocess": "localize"
+ },
+
+ "icons": {
+ "type": "object",
+ "optional": true,
+ "patternProperties": {
+ "^[1-9]\\d*$": { "type": "string" }
+ }
+ },
+
+ "incognito": {
+ "type": "string",
+ "enum": ["spanning"],
+ "optional": true,
+ "onError": "warn"
+ },
+
+ "background": {
+ "choices": [
+ {
+ "type": "object",
+ "properties": {
+ "page": { "$ref": "ExtensionURL" },
+ "persistent": {
+ "optional": true,
+ "$ref": "PersistentBackgroundProperty"
+ }
+ },
+ "additionalProperties": { "$ref": "UnrecognizedProperty" }
+ },
+ {
+ "type": "object",
+ "properties": {
+ "scripts": {
+ "type": "array",
+ "items": { "$ref": "ExtensionURL" }
+ },
+ "persistent": {
+ "optional": true,
+ "$ref": "PersistentBackgroundProperty"
+ }
+ },
+ "additionalProperties": { "$ref": "UnrecognizedProperty" }
+ }
+ ],
+ "optional": true
+ },
+
+ "options_ui": {
+ "type": "object",
+
+ "optional": true,
+
+ "properties": {
+ "page": { "$ref": "ExtensionURL" },
+ "browser_style": {
+ "type": "boolean",
+ "optional": true
+ },
+ "chrome_style": {
+ "type": "boolean",
+ "optional": true
+ },
+ "open_in_tab": {
+ "type": "boolean",
+ "optional": true
+ }
+ },
+
+ "additionalProperties": {
+ "type": "any",
+ "deprecated": "An unexpected property was found in the WebExtension manifest"
+ }
+ },
+
+ "content_scripts": {
+ "type": "array",
+ "optional": true,
+ "items": { "$ref": "ContentScript" }
+ },
+
+ "content_security_policy": {
+ "type": "string",
+ "optional": true,
+ "format": "contentSecurityPolicy",
+ "onError": "warn"
+ },
+
+ "permissions": {
+ "type": "array",
+ "items": {
+ "choices": [
+ { "$ref": "Permission" },
+ {
+ "type": "string",
+ "deprecated": "Unknown permission ${value}"
+ }
+ ]
+ },
+ "optional": true
+ },
+
+ "web_accessible_resources": {
+ "type": "array",
+ "items": { "type": "string" },
+ "optional": true
+ },
+
+ "developer": {
+ "type": "object",
+ "optional": true,
+ "properties": {
+ "name": {
+ "type": "string",
+ "optional": true,
+ "preprocess": "localize"
+ },
+ "url": {
+ "type": "string",
+ "optional": true,
+ "preprocess": "localize"
+ }
+ }
+ }
+
+ },
+
+ "additionalProperties": { "$ref": "UnrecognizedProperty" }
+ },
+ {
+ "id": "Permission",
+ "choices": [
+ {
+ "type": "string",
+ "enum": [
+ "alarms",
+ "clipboardWrite",
+ "idle",
+ "notifications",
+ "storage"
+ ]
+ },
+ { "$ref": "MatchPattern" }
+ ]
+ },
+ {
+ "id": "ExtensionURL",
+ "type": "string",
+ "format": "strictRelativeUrl"
+ },
+ {
+ "id": "ExtensionID",
+ "choices": [
+ {
+ "type": "string",
+ "pattern": "(?i)^\\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\}$"
+ },
+ {
+ "type": "string",
+ "pattern": "(?i)^[a-z0-9-._]*@[a-z0-9-._]+$"
+ }
+ ]
+ },
+ {
+ "id": "FirefoxSpecificProperties",
+ "type": "object",
+ "properties": {
+ "id": {
+ "$ref": "ExtensionID",
+ "optional": true
+ },
+
+ "update_url": {
+ "type": "string",
+ "format": "url",
+ "optional": true
+ },
+
+ "strict_min_version": {
+ "type": "string",
+ "optional": true
+ },
+
+ "strict_max_version": {
+ "type": "string",
+ "optional": true
+ }
+ }
+ },
+ {
+ "id": "MatchPattern",
+ "choices": [
+ {
+ "type": "string",
+ "enum": ["<all_urls>"]
+ },
+ {
+ "type": "string",
+ "pattern": "^(https?|file|ftp|\\*)://(\\*|\\*\\.[^*/]+|[^*/]+)/.*$"
+ },
+ {
+ "type": "string",
+ "pattern": "^file:///.*$"
+ }
+ ]
+ },
+ {
+ "id": "ContentScript",
+ "type": "object",
+ "description": "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. Based on InjectDetails, but using underscore rather than camel case naming conventions.",
+ "additionalProperties": { "$ref": "UnrecognizedProperty" },
+ "properties": {
+ "matches": {
+ "type": "array",
+ "optional": false,
+ "minItems": 1,
+ "items": { "$ref": "MatchPattern" }
+ },
+ "exclude_matches": {
+ "type": "array",
+ "optional": true,
+ "minItems": 1,
+ "items": { "$ref": "MatchPattern" }
+ },
+ "include_globs": {
+ "type": "array",
+ "optional": true,
+ "items": { "type": "string" }
+ },
+ "exclude_globs": {
+ "type": "array",
+ "optional": true,
+ "items": { "type": "string" }
+ },
+ "css": {
+ "type": "array",
+ "optional": true,
+ "description": "The list of CSS files to inject",
+ "items": { "$ref": "ExtensionURL" }
+ },
+ "js": {
+ "type": "array",
+ "optional": true,
+ "description": "The list of CSS files to inject",
+ "items": { "$ref": "ExtensionURL" }
+ },
+ "all_frames": {"type": "boolean", "optional": true, "description": "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."},
+ "match_about_blank": {"type": "boolean", "optional": true, "description": "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>."},
+ "run_at": {
+ "$ref": "extensionTypes.RunAt",
+ "optional": true,
+ "description": "The soonest that the JavaScript or CSS will be injected into the tab. Defaults to \"document_idle\"."
+ }
+ }
+ },
+ {
+ "id": "IconPath",
+ "choices": [
+ {
+ "type": "object",
+ "patternProperties": {
+ "^[1-9]\\d*$": { "$ref": "ExtensionURL" }
+ },
+ "additionalProperties": false
+ },
+ { "$ref": "ExtensionURL" }
+ ]
+ },
+ {
+ "id": "IconImageData",
+ "choices": [
+ {
+ "type": "object",
+ "patternProperties": {
+ "^[1-9]\\d*$": { "$ref": "ImageData" }
+ },
+ "additionalProperties": false
+ },
+ { "$ref": "ImageData" }
+ ]
+ },
+ {
+ "id": "ImageData",
+ "type": "object",
+ "isInstanceOf": "ImageData",
+ "postprocess": "convertImageDataToURL"
+ },
+ {
+ "id": "UnrecognizedProperty",
+ "type": "any",
+ "deprecated": "An unexpected property was found in the WebExtension manifest."
+ },
+ {
+ "id": "PersistentBackgroundProperty",
+ "type": "boolean",
+ "deprecated": "Event pages are not currently supported. This will run as a persistent background page."
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/moz.build b/toolkit/components/webextensions/schemas/moz.build
new file mode 100644
index 000000000..aac3a838c
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/moz.build
@@ -0,0 +1,7 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+JAR_MANIFESTS += ['jar.mn']
diff --git a/toolkit/components/webextensions/schemas/native_host_manifest.json b/toolkit/components/webextensions/schemas/native_host_manifest.json
new file mode 100644
index 000000000..4ad2ea7f1
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/native_host_manifest.json
@@ -0,0 +1,37 @@
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "id": "NativeHostManifest",
+ "type": "object",
+ "description": "Represents a native host manifest file",
+ "properties": {
+ "name": {
+ "type": "string",
+ "pattern": "^\\w+(\\.\\w+)*$"
+ },
+ "description": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "stdio"
+ ]
+ },
+ "allowed_extensions": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "manifest.ExtensionID"
+ }
+ }
+ }
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/notifications.json b/toolkit/components/webextensions/schemas/notifications.json
new file mode 100644
index 000000000..12878e8c8
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/notifications.json
@@ -0,0 +1,416 @@
+// 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.
+
+[
+ {
+ "namespace": "notifications",
+ "permissions": ["notifications"],
+ "types": [
+ {
+ "id": "TemplateType",
+ "type": "string",
+ "enum": [
+ "basic",
+ "image",
+ "list",
+ "progress"
+ ]
+ },
+ {
+ "id": "PermissionLevel",
+ "type": "string",
+ "enum": [
+ "granted",
+ "denied"
+ ]
+ },
+ {
+ "id": "NotificationItem",
+ "type": "object",
+ "properties": {
+ "title": {
+ "description": "Title of one item of a list notification.",
+ "type": "string"
+ },
+ "message": {
+ "description": "Additional details about this item.",
+ "type": "string"
+ }
+ }
+ },
+ {
+ "id": "CreateNotificationOptions",
+ "type": "object",
+ "properties": {
+ "type": {
+ "description": "Which type of notification to display.",
+ "$ref": "TemplateType"
+ },
+ "iconUrl": {
+ "optional": true,
+ "description": "A URL to the sender's avatar, app icon, or a thumbnail for image notifications.",
+ "type": "string"
+ },
+ "appIconMaskUrl": {
+ "optional": true,
+ "description": "A URL to the app icon mask.",
+ "type": "string"
+ },
+ "title": {
+ "description": "Title of the notification (e.g. sender name for email).",
+ "type": "string"
+ },
+ "message": {
+ "description": "Main notification content.",
+ "type": "string"
+ },
+ "contextMessage": {
+ "optional": true,
+ "description": "Alternate notification content with a lower-weight font.",
+ "type": "string"
+ },
+ "priority": {
+ "optional": true,
+ "description": "Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.",
+ "type": "integer",
+ "minimum": -2,
+ "maximum": 2
+ },
+ "eventTime": {
+ "optional": true,
+ "description": "A timestamp associated with the notification, in milliseconds past the epoch.",
+ "type": "number"
+ },
+ "buttons": {
+ "unsupported": true,
+ "optional": true,
+ "description": "Text and icons for up to two notification action buttons.",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "iconUrl": {
+ "optional": true,
+ "type": "string"
+ }
+ }
+ }
+ },
+ "imageUrl": {
+ "optional": true,
+ "description": "A URL to the image thumbnail for image-type notifications.",
+ "type": "string"
+ },
+ "items": {
+ "optional": true,
+ "description": "Items for multi-item notifications.",
+ "type": "array",
+ "items": { "$ref": "NotificationItem" }
+ },
+ "progress": {
+ "optional": true,
+ "description": "Current progress ranges from 0 to 100.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 100
+ },
+ "isClickable": {
+ "optional": true,
+ "description": "Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.",
+ "type": "boolean"
+ }
+ }
+ },
+ {
+ "id": "UpdateNotificationOptions",
+ "type": "object",
+ "properties": {
+ "type": {
+ "optional": true,
+ "description": "Which type of notification to display.",
+ "$ref": "TemplateType"
+ },
+ "iconUrl": {
+ "optional": true,
+ "description": "A URL to the sender's avatar, app icon, or a thumbnail for image notifications.",
+ "type": "string"
+ },
+ "appIconMaskUrl": {
+ "optional": true,
+ "description": "A URL to the app icon mask.",
+ "type": "string"
+ },
+ "title": {
+ "optional": true,
+ "description": "Title of the notification (e.g. sender name for email).",
+ "type": "string"
+ },
+ "message": {
+ "optional": true,
+ "description": "Main notification content.",
+ "type": "string"
+ },
+ "contextMessage": {
+ "optional": true,
+ "description": "Alternate notification content with a lower-weight font.",
+ "type": "string"
+ },
+ "priority": {
+ "optional": true,
+ "description": "Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.",
+ "type": "integer",
+ "minimum": -2,
+ "maximum": 2
+ },
+ "eventTime": {
+ "optional": true,
+ "description": "A timestamp associated with the notification, in milliseconds past the epoch.",
+ "type": "number"
+ },
+ "buttons": {
+ "unsupported": true,
+ "optional": true,
+ "description": "Text and icons for up to two notification action buttons.",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "iconUrl": {
+ "optional": true,
+ "type": "string"
+ }
+ }
+ }
+ },
+ "imageUrl": {
+ "optional": true,
+ "description": "A URL to the image thumbnail for image-type notifications.",
+ "type": "string"
+ },
+ "items": {
+ "optional": true,
+ "description": "Items for multi-item notifications.",
+ "type": "array",
+ "items": { "$ref": "NotificationItem" }
+ },
+ "progress": {
+ "optional": true,
+ "description": "Current progress ranges from 0 to 100.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 100
+ },
+ "isClickable": {
+ "optional": true,
+ "description": "Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.",
+ "type": "boolean"
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "create",
+ "type": "function",
+ "description": "Creates and displays a notification.",
+ "async": "callback",
+ "parameters": [
+ {
+ "optional": true,
+ "type": "string",
+ "name": "notificationId",
+ "description": "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."
+ },
+ {
+ "$ref": "CreateNotificationOptions",
+ "name": "options",
+ "description": "Contents of the notification."
+ },
+ {
+ "optional": true,
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "notificationId",
+ "type": "string",
+ "description": "The notification id (either supplied or generated) that represents the created notification."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "update",
+ "unsupported": true,
+ "type": "function",
+ "description": "Updates an existing notification.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "notificationId",
+ "description": "The id of the notification to be updated."
+ },
+ {
+ "$ref": "UpdateNotificationOptions",
+ "name": "options",
+ "description": "Contents of the notification to update to."
+ },
+ {
+ "optional": true,
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "wasUpdated",
+ "type": "boolean",
+ "description": "Indicates whether a matching notification existed."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "clear",
+ "type": "function",
+ "description": "Clears an existing notification.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "notificationId",
+ "description": "The id of the notification to be updated."
+ },
+ {
+ "optional": true,
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "wasCleared",
+ "type": "boolean",
+ "description": "Indicates whether a matching notification existed."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getAll",
+ "type": "function",
+ "description": "Retrieves all the notifications.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "notifications",
+ "type": "object",
+ "description": "The set of notifications currently in the system."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getPermissionLevel",
+ "unsupported": true,
+ "type": "function",
+ "description": "Retrieves whether the user has enabled notifications from this app or extension.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "level",
+ "$ref": "PermissionLevel",
+ "description": "The current permission level."
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onClosed",
+ "type": "function",
+ "description": "Fired when the notification closed, either by the system or by user action.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "notificationId",
+ "description": "The notificationId of the closed notification."
+ },
+ {
+ "type": "boolean",
+ "name": "byUser",
+ "description": "True if the notification was closed by the user."
+ }
+ ]
+ },
+ {
+ "name": "onClicked",
+ "type": "function",
+ "description": "Fired when the user clicked in a non-button area of the notification.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "notificationId",
+ "description": "The notificationId of the clicked notification."
+ }
+ ]
+ },
+ {
+ "name": "onButtonClicked",
+ "type": "function",
+ "description": "Fired when the user pressed a button in the notification.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "notificationId",
+ "description": "The notificationId of the clicked notification."
+ },
+ {
+ "type": "number",
+ "name": "buttonIndex",
+ "description": "The index of the button clicked by the user."
+ }
+ ]
+ },
+ {
+ "name": "onPermissionLevelChanged",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when the user changes the permission level.",
+ "parameters": [
+ {
+ "$ref": "PermissionLevel",
+ "name": "level",
+ "description": "The new permission level."
+ }
+ ]
+ },
+ {
+ "name": "onShowSettings",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when the user clicked on a link for the app's notification settings.",
+ "parameters": [
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/runtime.json b/toolkit/components/webextensions/schemas/runtime.json
new file mode 100644
index 000000000..b3f12a768
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/runtime.json
@@ -0,0 +1,592 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "nativeMessaging"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "runtime",
+ "allowedContexts": ["content"],
+ "description": "Use the <code>browser.runtime</code> API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs.",
+ "types": [
+ {
+ "id": "Port",
+ "type": "object",
+ "allowedContexts": ["content"],
+ "description": "An object which allows two way communication with other pages.",
+ "properties": {
+ "name": {"type": "string"},
+ "disconnect": { "type": "function" },
+ "onDisconnect": { "$ref": "events.Event" },
+ "onMessage": { "$ref": "events.Event" },
+ "postMessage": {"type": "function"},
+ "sender": {
+ "$ref": "MessageSender",
+ "optional": true,
+ "description": "This property will <b>only</b> be present on ports passed to onConnect/onConnectExternal listeners."
+ }
+ },
+ "additionalProperties": { "type": "any"}
+ },
+ {
+ "id": "MessageSender",
+ "type": "object",
+ "allowedContexts": ["content"],
+ "description": "An object containing information about the script context that sent a message or request.",
+ "properties": {
+ "tab": {"$ref": "tabs.Tab", "optional": true, "description": "The $(ref:tabs.Tab) which opened the connection, if any. This property will <strong>only</strong> be present when the connection was opened from a tab (including content scripts), and <strong>only</strong> if the receiver is an extension, not an app."},
+ "frameId": {"type": "integer", "optional": true, "description": "The $(topic:frame_ids)[frame] that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when <code>tab</code> is set."},
+ "id": {"type": "string", "optional": true, "description": "The ID of the extension or app that opened the connection, if any."},
+ "url": {"type": "string", "optional": true, "description": "The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it."},
+ "tlsChannelId": {"unsupported": true, "type": "string", "optional": true, "description": "The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, and if available."}
+ }
+ },
+ {
+ "id": "PlatformOs",
+ "type": "string",
+ "allowedContexts": ["content"],
+ "description": "The operating system the browser is running on.",
+ "enum": ["mac", "win", "android", "cros", "linux", "openbsd"]
+ },
+ {
+ "id": "PlatformArch",
+ "type": "string",
+ "enum": ["arm", "x86-32", "x86-64"],
+ "allowedContexts": ["content"],
+ "description": "The machine's processor architecture."
+ },
+ {
+ "id": "PlatformInfo",
+ "type": "object",
+ "allowedContexts": ["content"],
+ "description": "An object containing information about the current platform.",
+ "properties": {
+ "os": {
+ "$ref": "PlatformOs",
+ "description": "The operating system the browser is running on."
+ },
+ "arch": {
+ "$ref": "PlatformArch",
+ "description": "The machine's processor architecture."
+ },
+ "nacl_arch" : {
+ "unsupported": true,
+ "description": "The native client architecture. This may be different from arch on some platforms.",
+ "$ref": "PlatformNaclArch"
+ }
+ }
+ },
+ {
+ "id": "BrowserInfo",
+ "type": "object",
+ "description": "An object containing information about the current browser.",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The name of the browser, for example 'Firefox'."
+ },
+ "vendor": {
+ "type": "string",
+ "description": "The name of the browser vendor, for example 'Mozilla'."
+ },
+ "version": {
+ "type": "string",
+ "description": "The browser's version, for example '42.0.0' or '0.8.1pre'."
+ },
+ "buildID": {
+ "type": "string",
+ "description": "The browser's build ID/date, for example '20160101'."
+ }
+ }
+ },
+ {
+ "id": "RequestUpdateCheckStatus",
+ "type": "string",
+ "enum": ["throttled", "no_update", "update_available"],
+ "allowedContexts": ["content"],
+ "description": "Result of the update check."
+ },
+ {
+ "id": "OnInstalledReason",
+ "type": "string",
+ "enum": ["install", "update", "browser_update"],
+ "allowedContexts": ["content"],
+ "description": "The reason that this event is being dispatched."
+ },
+ {
+ "id": "OnRestartRequiredReason",
+ "type": "string",
+ "allowedContexts": ["content"],
+ "description": "The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the application is updated to a newer version. 'os_update' is used when the restart is needed because the browser/OS is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in the enterprise policy.",
+ "enum": ["app_update", "os_update", "periodic"]
+ }
+ ],
+ "properties": {
+ "lastError": {
+ "type": "object",
+ "optional": true,
+ "allowedContexts": ["content"],
+ "description": "This will be defined during an API method callback if there was an error",
+ "properties": {
+ "message": {
+ "optional": true,
+ "type": "string",
+ "description": "Details about the error which occurred."
+ }
+ },
+ "additionalProperties": {
+ "type": "any"
+ }
+ },
+ "id": {
+ "type": "string",
+ "allowedContexts": ["content"],
+ "description": "The ID of the extension/app."
+ }
+ },
+ "functions": [
+ {
+ "name": "getBackgroundPage",
+ "type": "function",
+ "description": "Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "backgroundPage",
+ "optional": true,
+ "type": "object",
+ "isInstanceOf": "Window",
+ "additionalProperties": { "type": "any" },
+ "description": "The JavaScript 'window' object for the background page."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "openOptionsPage",
+ "type": "function",
+ "description": "<p>Open your Extension's options page, if possible.</p><p>The precise behavior may depend on your manifest's <code>$(topic:optionsV2)[options_ui]</code> or <code>$(topic:options)[options_page]</code> key, or what the browser happens to support at the time.</p><p>If your Extension does not declare an options page, or the browser failed to create one for some other reason, the callback will set $(ref:lastError).</p>",
+ "async": "callback",
+ "parameters": [{
+ "type": "function",
+ "name": "callback",
+ "parameters": [],
+ "optional": true
+ }]
+ },
+ {
+ "name": "getManifest",
+ "allowedContexts": ["content"],
+ "description": "Returns details about the app or extension from the manifest. The object returned is a serialization of the full $(topic:manifest)[manifest file].",
+ "type": "function",
+ "parameters": [],
+ "returns": {
+ "type": "object",
+ "properties": {},
+ "additionalProperties": { "type": "any" },
+ "description": "The manifest details."
+ }
+ },
+ {
+ "name": "getURL",
+ "type": "function",
+ "allowedContexts": ["content"],
+ "description": "Converts a relative path within an app/extension install directory to a fully-qualified URL.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "path",
+ "description": "A path to a resource within an app/extension expressed relative to its install directory."
+ }
+ ],
+ "returns": {
+ "type": "string",
+ "description": "The fully-qualified URL to the resource."
+ }
+ },
+ {
+ "name": "setUninstallURL",
+ "type": "function",
+ "description": "Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "url",
+ "maxLength": 255,
+ "description": "URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation."
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "description": "Called when the uninstall URL is set. If the given URL is invalid, $(ref:runtime.lastError) will be set.",
+ "parameters": []
+ }
+ ]
+ },
+ {
+ "name": "reload",
+ "description": "Reloads the app or extension.",
+ "type": "function",
+ "parameters": []
+ },
+ {
+ "name": "requestUpdateCheck",
+ "unsupported": true,
+ "type": "function",
+ "description": "Requests an update check for this app/extension.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "status",
+ "$ref": "RequestUpdateCheckStatus",
+ "description": "Result of the update check."
+ },
+ {
+ "name": "details",
+ "type": "object",
+ "optional": true,
+ "properties": {
+ "version": {
+ "type": "string",
+ "description": "The version of the available update."
+ }
+ },
+ "description": "If an update is available, this contains more information about the available update."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "restart",
+ "unsupported": true,
+ "description": "Restart the device when the app runs in kiosk mode. Otherwise, it's no-op.",
+ "type": "function",
+ "parameters": []
+ },
+ {
+ "name": "connect",
+ "type": "function",
+ "allowedContexts": ["content"],
+ "description": "Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and $(topic:manifest/externally_connectable)[web messaging]. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via $(ref:tabs.connect).",
+ "parameters": [
+ {"type": "string", "name": "extensionId", "optional": true, "description": "The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for $(topic:manifest/externally_connectable)[web messaging]."},
+ {
+ "type": "object",
+ "name": "connectInfo",
+ "properties": {
+ "name": { "type": "string", "optional": true, "description": "Will be passed into onConnect for processes that are listening for the connection event." },
+ "includeTlsChannelId": { "type": "boolean", "optional": true, "description": "Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event." }
+ },
+ "optional": true
+ }
+ ],
+ "returns": {
+ "$ref": "Port",
+ "description": "Port through which messages can be sent and received. The port's $(ref:runtime.Port onDisconnect) event is fired if the extension/app does not exist. "
+ }
+ },
+ {
+ "name": "connectNative",
+ "type": "function",
+ "description": "Connects to a native application in the host machine.",
+ "permissions": ["nativeMessaging"],
+ "parameters": [
+ {
+ "type": "string",
+ "name": "application",
+ "description": "The name of the registered application to connect to."
+ }
+ ],
+ "returns": {
+ "$ref": "Port",
+ "description": "Port through which messages can be sent and received with the application"
+ }
+ },
+ {
+ "name": "sendMessage",
+ "type": "function",
+ "allowAmbiguousOptionalArguments": true,
+ "allowedContexts": ["content"],
+ "description": "Sends a single message to event listeners within your extension/app or a different extension/app. Similar to $(ref:runtime.connect) but only sends a single message, with an optional response. If sending to your extension, the $(ref:runtime.onMessage) event will be fired in each page, or $(ref:runtime.onMessageExternal), if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use $(ref:tabs.sendMessage).",
+ "async": "responseCallback",
+ "parameters": [
+ {"type": "string", "name": "extensionId", "optional": true, "description": "The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for $(topic:manifest/externally_connectable)[web messaging]."},
+ { "type": "any", "name": "message" },
+ {
+ "type": "object",
+ "name": "options",
+ "properties": {
+ "includeTlsChannelId": { "type": "boolean", "optional": true, "description": "Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the connection event." }
+ },
+ "optional": true
+ },
+ {
+ "type": "function",
+ "name": "responseCallback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "response",
+ "type": "any",
+ "description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "sendNativeMessage",
+ "type": "function",
+ "description": "Send a single message to a native application.",
+ "permissions": ["nativeMessaging"],
+ "async": "responseCallback",
+ "parameters": [
+ {
+ "name": "application",
+ "description": "The name of the native messaging host.",
+ "type": "string"
+ },
+ {
+ "name": "message",
+ "description": "The message that will be passed to the native messaging host.",
+ "type": "any"
+ },
+ {
+ "type": "function",
+ "name": "responseCallback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "response",
+ "type": "any",
+ "description": "The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getBrowserInfo",
+ "type": "function",
+ "description": "Returns information about the current browser.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "description": "Called with results",
+ "parameters": [
+ {
+ "name": "browserInfo",
+ "$ref": "BrowserInfo"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getPlatformInfo",
+ "type": "function",
+ "description": "Returns information about the current platform.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "description": "Called with results",
+ "parameters": [
+ {
+ "name": "platformInfo",
+ "$ref": "PlatformInfo"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getPackageDirectoryEntry",
+ "unsupported": true,
+ "type": "function",
+ "description": "Returns a DirectoryEntry for the package directory.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "directoryEntry",
+ "type": "object",
+ "additionalProperties": { "type": "any" },
+ "isInstanceOf": "DirectoryEntry"
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onStartup",
+ "type": "function",
+ "description": "Fired when a profile that has this extension installed first starts up. This event is not fired for incognito profiles."
+ },
+ {
+ "name": "onInstalled",
+ "type": "function",
+ "description": "Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "reason": {
+ "$ref": "OnInstalledReason",
+ "description": "The reason that this event is being dispatched."
+ },
+ "previousVersion": {
+ "type": "string",
+ "optional": true,
+ "unsupported": true,
+ "description": "Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'."
+ },
+ "id": {
+ "type": "string",
+ "optional": true,
+ "unsupported": true,
+ "description": "Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'."
+ }
+ }
+ }
+ ]
+ },
+ {
+ "name": "onSuspend",
+ "unsupported": true,
+ "type": "function",
+ "description": "Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. "
+ },
+ {
+ "name": "onSuspendCanceled",
+ "unsupported": true,
+ "type": "function",
+ "description": "Sent after onSuspend to indicate that the app won't be unloaded after all."
+ },
+ {
+ "name": "onUpdateAvailable",
+ "type": "function",
+ "description": "Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call $(ref:runtime.reload). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call $(ref:runtime.reload) manually in response to this event the update will not get installed until the next time the browser itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if $(ref:runtime.reload) is called in response to this event.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "version": {
+ "type": "string",
+ "description": "The version number of the available update."
+ }
+ },
+ "additionalProperties": { "type": "any" },
+ "description": "The manifest details of the available update."
+ }
+ ]
+ },
+ {
+ "name": "onBrowserUpdateAvailable",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.",
+ "deprecated": "Please use $(ref:runtime.onRestartRequired).",
+ "parameters": []
+ },
+ {
+ "name": "onConnect",
+ "type": "function",
+ "allowedContexts": ["content"],
+ "description": "Fired when a connection is made from either an extension process or a content script.",
+ "parameters": [
+ {"$ref": "Port", "name": "port"}
+ ]
+ },
+ {
+ "name": "onConnectExternal",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when a connection is made from another extension.",
+ "parameters": [
+ {"$ref": "Port", "name": "port"}
+ ]
+ },
+ {
+ "name": "onMessage",
+ "type": "function",
+ "allowedContexts": ["content"],
+ "description": "Fired when a message is sent from either an extension process or a content script.",
+ "parameters": [
+ {"name": "message", "type": "any", "optional": true, "description": "The message sent by the calling script."},
+ {"name": "sender", "$ref": "MessageSender" },
+ {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one <code>onMessage</code> listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until <code>sendResponse</code> is called)." }
+ ],
+ "returns": {
+ "type": "boolean",
+ "optional": true,
+ "description": "Return true from the event listener if you wish to call <code>sendResponse</code> after the event listener returns."
+ }
+ },
+ {
+ "name": "onMessageExternal",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when a message is sent from another extension/app. Cannot be used in a content script.",
+ "parameters": [
+ {"name": "message", "type": "any", "optional": true, "description": "The message sent by the calling script."},
+ {"name": "sender", "$ref": "MessageSender" },
+ {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one <code>onMessage</code> listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until <code>sendResponse</code> is called)." }
+ ],
+ "returns": {
+ "type": "boolean",
+ "optional": true,
+ "description": "Return true from the event listener if you wish to call <code>sendResponse</code> after the event listener returns."
+ }
+ },
+ {
+ "name": "onRestartRequired",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps.",
+ "parameters": [
+ {
+ "$ref": "OnRestartRequiredReason",
+ "name": "reason",
+ "description": "The reason that the event is being dispatched."
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/storage.json b/toolkit/components/webextensions/schemas/storage.json
new file mode 100644
index 000000000..a54a20942
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/storage.json
@@ -0,0 +1,229 @@
+// 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.
+
+[
+ {
+ "namespace": "storage",
+ "allowedContexts": ["content"],
+ "defaultContexts": ["content"],
+ "description": "Use the <code>browser.storage</code> API to store, retrieve, and track changes to user data.",
+ "permissions": ["storage"],
+ "types": [
+ {
+ "id": "StorageChange",
+ "type": "object",
+ "properties": {
+ "oldValue": {
+ "type": "any",
+ "description": "The old value of the item, if there was an old value.",
+ "optional": true
+ },
+ "newValue": {
+ "type": "any",
+ "description": "The new value of the item, if there is a new value.",
+ "optional": true
+ }
+ }
+ },
+ {
+ "id": "StorageArea",
+ "type": "object",
+ "functions": [
+ {
+ "name": "get",
+ "type": "function",
+ "description": "Gets one or more items from storage.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "keys",
+ "choices": [
+ { "type": "string" },
+ { "type": "array", "items": { "type": "string" } },
+ {
+ "type": "object",
+ "description": "Storage items to return in the callback, where the values are replaced with those from storage if they exist.",
+ "additionalProperties": { "type": "any" }
+ }
+ ],
+ "description": "A single key to get, list of keys to get, or a dictionary specifying default values (see description of the object). An empty list or object will return an empty result object. Pass in <code>null</code> to get the entire contents of storage.",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Callback with storage items, or on failure (in which case $(ref:runtime.lastError) will be set).",
+ "parameters": [
+ {
+ "name": "items",
+ "type": "object",
+ "additionalProperties": { "type": "any" },
+ "description": "Object with items in their key-value mappings."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getBytesInUse",
+ "unsupported": true,
+ "type": "function",
+ "description": "Gets the amount of space (in bytes) being used by one or more items.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "keys",
+ "choices": [
+ { "type": "string" },
+ { "type": "array", "items": { "type": "string" } }
+ ],
+ "description": "A single key or list of keys to get the total usage for. An empty list will return 0. Pass in <code>null</code> to get the total usage of all of storage.",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Callback with the amount of space being used by storage, or on failure (in which case $(ref:runtime.lastError) will be set).",
+ "parameters": [
+ {
+ "name": "bytesInUse",
+ "type": "integer",
+ "description": "Amount of space being used in storage, in bytes."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "set",
+ "type": "function",
+ "description": "Sets multiple items.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "items",
+ "type": "object",
+ "additionalProperties": { "type": "any" },
+ "description": "<p>An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected.</p><p>Primitive values such as numbers will serialize as expected. Values with a <code>typeof</code> <code>\"object\"</code> and <code>\"function\"</code> will typically serialize to <code>{}</code>, with the exception of <code>Array</code> (serializes as expected), <code>Date</code>, and <code>Regex</code> (serialize using their <code>String</code> representation).</p>"
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).",
+ "parameters": [],
+ "optional": true
+ }
+ ]
+ },
+ {
+ "name": "remove",
+ "type": "function",
+ "description": "Removes one or more items from storage.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "keys",
+ "choices": [
+ {"type": "string"},
+ {"type": "array", "items": {"type": "string"}}
+ ],
+ "description": "A single key or a list of keys for items to remove."
+ },
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).",
+ "parameters": [],
+ "optional": true
+ }
+ ]
+ },
+ {
+ "name": "clear",
+ "type": "function",
+ "description": "Removes all items from storage.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).",
+ "parameters": [],
+ "optional": true
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onChanged",
+ "type": "function",
+ "description": "Fired when one or more items change.",
+ "parameters": [
+ {
+ "name": "changes",
+ "type": "object",
+ "additionalProperties": { "$ref": "StorageChange" },
+ "description": "Object mapping each key that changed to its corresponding $(ref:storage.StorageChange) for that item."
+ },
+ {
+ "name": "areaName",
+ "type": "string",
+ "description": "The name of the storage area (<code>\"sync\"</code>, <code>\"local\"</code> or <code>\"managed\"</code>) the changes are for."
+ }
+ ]
+ }
+ ],
+ "properties": {
+ "sync": {
+ "$ref": "StorageArea",
+ "description": "Items in the <code>sync</code> storage area are synced by the browser.",
+ "properties": {
+ "QUOTA_BYTES": {
+ "value": 102400,
+ "description": "The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError)."
+ },
+ "QUOTA_BYTES_PER_ITEM": {
+ "value": 8192,
+ "description": "The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set $(ref:runtime.lastError)."
+ },
+ "MAX_ITEMS": {
+ "value": 512,
+ "description": "The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set $(ref:runtime.lastError)."
+ },
+ "MAX_WRITE_OPERATIONS_PER_HOUR": {
+ "value": 1800,
+ "description": "<p>The maximum number of <code>set</code>, <code>remove</code>, or <code>clear</code> operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit.</p><p>Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError).</p>"
+ },
+ "MAX_WRITE_OPERATIONS_PER_MINUTE": {
+ "value": 120,
+ "description": "<p>The maximum number of <code>set</code>, <code>remove</code>, or <code>clear</code> operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time.</p><p>Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError).</p>"
+ },
+ "MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE": {
+ "value": 1000000,
+ "deprecated": "The storage.sync API no longer has a sustained write operation quota.",
+ "description": ""
+ }
+ }
+ },
+ "local": {
+ "$ref": "StorageArea",
+ "description": "Items in the <code>local</code> storage area are local to each machine.",
+ "properties": {
+ "QUOTA_BYTES": {
+ "value": 5242880,
+ "description": "The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the <code>unlimitedStorage</code> permission. Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError)."
+ }
+ }
+ },
+ "managed": {
+ "unsupported": true,
+ "$ref": "StorageArea",
+ "description": "Items in the <code>managed</code> storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error."
+ }
+ }
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/test.json b/toolkit/components/webextensions/schemas/test.json
new file mode 100644
index 000000000..25a62a96b
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/test.json
@@ -0,0 +1,215 @@
+// 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.
+
+[
+ {
+ "namespace": "test",
+ "allowedContexts": ["content"],
+ "defaultContexts": ["content"],
+ "description": "none",
+ "functions": [
+ {
+ "name": "notifyFail",
+ "type": "function",
+ "description": "Notifies the browser process that test code running in the extension failed. This is only used for internal unit testing.",
+ "parameters": [
+ {"type": "string", "name": "message"}
+ ]
+ },
+ {
+ "name": "notifyPass",
+ "type": "function",
+ "description": "Notifies the browser process that test code running in the extension passed. This is only used for internal unit testing.",
+ "parameters": [
+ {"type": "string", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "log",
+ "type": "function",
+ "description": "Logs a message during internal unit testing.",
+ "parameters": [
+ {"type": "string", "name": "message"}
+ ]
+ },
+ {
+ "name": "sendMessage",
+ "type": "function",
+ "description": "Sends a string message to the browser process, generating a Notification that C++ test code can wait for.",
+ "allowAmbiguousOptionalArguments": true,
+ "parameters": [
+ {"type": "any", "name": "arg1", "optional": true},
+ {"type": "any", "name": "arg2", "optional": true}
+ ]
+ },
+ {
+ "name": "fail",
+ "type": "function",
+ "parameters": [
+ {"type": "any", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "succeed",
+ "type": "function",
+ "parameters": [
+ {"type": "any", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "assertTrue",
+ "type": "function",
+ "allowAmbiguousOptionalArguments": true,
+ "parameters": [
+ {"name": "test", "type": "any", "optional": true},
+ {"type": "string", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "assertFalse",
+ "type": "function",
+ "allowAmbiguousOptionalArguments": true,
+ "parameters": [
+ {"name": "test", "type": "any", "optional": true},
+ {"type": "string", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "assertBool",
+ "type": "function",
+ "unsupported": true,
+ "parameters": [
+ {
+ "name": "test",
+ "choices": [
+ {"type": "string"},
+ {"type": "boolean"}
+ ]
+ },
+ {"type": "boolean", "name": "expected"},
+ {"type": "string", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "checkDeepEq",
+ "type": "function",
+ "unsupported": true,
+ "allowAmbiguousOptionalArguments": true,
+ "parameters": [
+ {"type": "any", "name": "expected"},
+ {"type": "any", "name": "actual"}
+ ]
+ },
+ {
+ "name": "assertEq",
+ "type": "function",
+ "allowAmbiguousOptionalArguments": true,
+ "parameters": [
+ {"type": "any", "name": "expected", "optional": true},
+ {"type": "any", "name": "actual", "optional": true},
+ {"type": "string", "name": "message", "optional": true}
+ ]
+ },
+ {
+ "name": "assertNoLastError",
+ "type": "function",
+ "unsupported": true,
+ "parameters": []
+ },
+ {
+ "name": "assertLastError",
+ "type": "function",
+ "unsupported": true,
+ "parameters": [
+ {"type": "string", "name": "expectedError"}
+ ]
+ },
+ {
+ "name": "assertRejects",
+ "type": "function",
+ "async": true,
+ "parameters": [
+ {
+ "name": "promise",
+ "$ref": "Promise"
+ },
+ {
+ "name": "expectedError",
+ "$ref": "ExpectedError",
+ "optional": true
+ },
+ {
+ "name": "message",
+ "type": "string",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "name": "assertThrows",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "func",
+ "type": "function"
+ },
+ {
+ "name": "expectedError",
+ "$ref": "ExpectedError",
+ "optional": true
+ },
+ {
+ "name": "message",
+ "type": "string",
+ "optional": true
+ }
+ ]
+ }
+ ],
+ "types": [
+ {
+ "id": "ExpectedError",
+ "choices": [
+ {"type": "string"},
+ {"type": "object", "isInstanceOf": "RegExp", "additionalProperties": true},
+ {"type": "function"}
+ ]
+ },
+ {
+ "id": "Promise",
+ "choices": [
+ {
+ "type": "object",
+ "properties": {
+ "then": {"type": "function"}
+ },
+ "additionalProperties": true
+ },
+ {
+ "type": "object",
+ "isInstanceOf": "Promise",
+ "additionalProperties": true
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onMessage",
+ "type": "function",
+ "description": "Used to test sending messages to extensions.",
+ "parameters": [
+ {
+ "type": "string",
+ "name": "message"
+ },
+ {
+ "type": "any",
+ "name": "argument"
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/top_sites.json b/toolkit/components/webextensions/schemas/top_sites.json
new file mode 100644
index 000000000..fbfbc4b62
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/top_sites.json
@@ -0,0 +1,66 @@
+/* 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/. */
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "topSites"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "topSites",
+ "description": "Use the chrome.topSites API to access the top sites that are displayed on the new tab page. ",
+ "permissions": ["topSites"],
+ "types": [
+ {
+ "id": "MostVisitedURL",
+ "type": "object",
+ "description": "An object encapsulating a most visited URL, such as the URLs on the new tab page.",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "The most visited URL."
+ },
+ "title": {
+ "type": "string",
+ "optional": true,
+ "description": "The title of the page."
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "get",
+ "type": "function",
+ "description": "Gets a list of top sites.",
+ "async": "callback",
+ "parameters": [
+ {
+ "name": "callback",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "results",
+ "type": "array",
+ "items": {
+ "$ref": "MostVisitedURL"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/web_navigation.json b/toolkit/components/webextensions/schemas/web_navigation.json
new file mode 100644
index 000000000..1e13b181a
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/web_navigation.json
@@ -0,0 +1,387 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "webNavigation"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "webNavigation",
+ "description": "Use the <code>browser.webNavigation</code> API to receive notifications about the status of navigation requests in-flight.",
+ "permissions": ["webNavigation"],
+ "types": [
+ {
+ "id": "TransitionType",
+ "type": "string",
+ "enum": ["link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "start_page", "form_submit", "reload", "keyword", "keyword_generated"],
+ "description": "Cause of the navigation. The same transition types as defined in the history API are used. These are the same transition types as defined in the $(topic:transition_types)[history API] except with <code>\"start_page\"</code> in place of <code>\"auto_toplevel\"</code> (for backwards compatibility)."
+ },
+ {
+ "id": "TransitionQualifier",
+ "type": "string",
+ "enum": ["client_redirect", "server_redirect", "forward_back", "from_address_bar"]
+ },
+ {
+ "id": "EventUrlFilters",
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "events.UrlFilter" }
+ }
+ }
+ }
+ ],
+ "functions": [
+ {
+ "name": "getFrame",
+ "type": "function",
+ "description": "Retrieves information about the given frame. A frame refers to an &lt;iframe&gt; or a &lt;frame&gt; of a web page and is identified by a tab ID and a frame ID.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Information about the frame to retrieve information about.",
+ "properties": {
+ "tabId": { "type": "integer", "minimum": 0, "description": "The ID of the tab in which the frame is." },
+ "processId": {"optional": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": { "type": "integer", "minimum": 0, "description": "The ID of the frame in the given tab." }
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "optional": true,
+ "description": "Information about the requested frame, null if the specified frame ID and/or tab ID are invalid.",
+ "properties": {
+ "errorOccurred": {
+ "unsupported": true,
+ "type": "boolean",
+ "description": "True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL currently associated with this frame, if the frame identified by the frameId existed at one point in the given tab. The fact that an URL is associated with a given frameId does not imply that the corresponding frame still exists."
+ },
+ "parentFrameId": {
+ "type": "integer",
+ "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists."
+ }
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "name": "getAllFrames",
+ "type": "function",
+ "description": "Retrieves information about all frames of a given tab.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "description": "Information about the tab to retrieve all frames from.",
+ "properties": {
+ "tabId": { "type": "integer", "minimum": 0, "description": "The ID of the tab." }
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "details",
+ "type": "array",
+ "description": "A list of frames in the given tab, null if the specified tab ID is invalid.",
+ "optional": true,
+ "items": {
+ "type": "object",
+ "properties": {
+ "errorOccurred": {
+ "unsupported": true,
+ "type": "boolean",
+ "description": "True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired."
+ },
+ "processId": {
+ "unsupported": true,
+ "type": "integer",
+ "description": "The ID of the process runs the renderer for this tab."
+ },
+ "frameId": {
+ "type": "integer",
+ "description": "The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe."
+ },
+ "parentFrameId": {
+ "type": "integer",
+ "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL currently associated with this frame."
+ }
+ }
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onBeforeNavigate",
+ "type": "function",
+ "description": "Fired when a navigation is about to occur.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation is about to occur."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique for a given tab and process."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists."},
+ "timeStamp": {"type": "number", "description": "The time when the browser was about to start the navigation, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onCommitted",
+ "type": "function",
+ "description": "Fired when a navigation is committed. The document (and the resources it refers to, such as images and subframes) might still be downloading, but at least part of the document has been received from the server and the browser has decided to switch to the new document.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."},
+ "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}},
+ "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onDOMContentLoaded",
+ "type": "function",
+ "description": "Fired when the page's DOM is fully constructed, but the referenced resources may not finish loading.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "timeStamp": {"type": "number", "description": "The time when the page's DOM was fully constructed, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onCompleted",
+ "type": "function",
+ "description": "Fired when a document, including the resources it refers to, is completely loaded and initialized.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "timeStamp": {"type": "number", "description": "The time when the document finished loading, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onErrorOccurred",
+ "type": "function",
+ "description": "Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "error": {"unsupported": true, "type": "string", "description": "The error description."},
+ "timeStamp": {"type": "number", "description": "The time when the error occurred, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onCreatedNavigationTarget",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when a new window, or a new tab in an existing window, is created to host a navigation.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "sourceTabId": {"type": "integer", "description": "The ID of the tab in which the navigation is triggered."},
+ "sourceProcessId": {"type": "integer", "description": "The ID of the process runs the renderer for the source tab."},
+ "sourceFrameId": {"type": "integer", "description": "The ID of the frame with sourceTabId in which the navigation is triggered. 0 indicates the main frame."},
+ "url": {"type": "string", "description": "The URL to be opened in the new window."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the url is opened"},
+ "timeStamp": {"type": "number", "description": "The time when the browser was about to create a new view, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onReferenceFragmentUpdated",
+ "type": "function",
+ "description": "Fired when the reference fragment of a frame was updated. All future events for that frame will use the updated URL.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."},
+ "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}},
+ "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ },
+ {
+ "name": "onTabReplaced",
+ "type": "function",
+ "description": "Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "replacedTabId": {"type": "integer", "description": "The ID of the tab that was replaced."},
+ "tabId": {"type": "integer", "description": "The ID of the tab that replaced the old tab."},
+ "timeStamp": {"type": "number", "description": "The time when the replacement happened, in milliseconds since the epoch."}
+ }
+ }
+ ]
+ },
+ {
+ "name": "onHistoryStateUpdated",
+ "type": "function",
+ "description": "Fired when the frame's history was updated to a new URL. All future events for that frame will use the updated URL.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."},
+ "url": {"type": "string"},
+ "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."},
+ "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."},
+ "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."},
+ "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}},
+ "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "name": "filters",
+ "optional": true,
+ "$ref": "EventUrlFilters",
+ "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event."
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/schemas/web_request.json b/toolkit/components/webextensions/schemas/web_request.json
new file mode 100644
index 000000000..4035aea6e
--- /dev/null
+++ b/toolkit/components/webextensions/schemas/web_request.json
@@ -0,0 +1,616 @@
+// 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.
+
+[
+ {
+ "namespace": "manifest",
+ "types": [
+ {
+ "$extend": "Permission",
+ "choices": [{
+ "type": "string",
+ "enum": [
+ "webRequest",
+ "webRequestBlocking"
+ ]
+ }]
+ }
+ ]
+ },
+ {
+ "namespace": "webRequest",
+ "description": "Use the <code>browser.webRequest</code> API to observe and analyze traffic and to intercept, block, or modify requests in-flight.",
+ "permissions": ["webRequest"],
+ "properties": {
+ "MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES": {
+ "value": 20,
+ "description": "The maximum number of times that <code>handlerBehaviorChanged</code> can be called per 10 minute sustained interval. <code>handlerBehaviorChanged</code> is an expensive function call that shouldn't be called often."
+ }
+ },
+ "types": [
+ {
+ "id": "ResourceType",
+ "type": "string",
+ "enum": [
+ "main_frame",
+ "sub_frame",
+ "stylesheet",
+ "script",
+ "image",
+ "object",
+ "xmlhttprequest",
+ "xbl",
+ "xslt",
+ "ping",
+ "beacon",
+ "xml_dtd",
+ "font",
+ "media",
+ "websocket",
+ "csp_report",
+ "imageset",
+ "web_manifest",
+ "other"
+ ]
+ },
+ {
+ "id": "OnBeforeRequestOptions",
+ "type": "string",
+ "enum": ["blocking", "requestBody"]
+ },
+ {
+ "id": "OnBeforeSendHeadersOptions",
+ "type": "string",
+ "enum": ["requestHeaders", "blocking"]
+ },
+ {
+ "id": "OnSendHeadersOptions",
+ "type": "string",
+ "enum": ["requestHeaders"]
+ },
+ {
+ "id": "OnHeadersReceivedOptions",
+ "type": "string",
+ "enum": ["blocking", "responseHeaders"]
+ },
+ {
+ "id": "OnAuthRequiredOptions",
+ "type": "string",
+ "enum": ["responseHeaders", "blocking", "asyncBlocking"]
+ },
+ {
+ "id": "OnResponseStartedOptions",
+ "type": "string",
+ "enum": ["responseHeaders"]
+ },
+ {
+ "id": "OnBeforeRedirectOptions",
+ "type": "string",
+ "enum": ["responseHeaders"]
+ },
+ {
+ "id": "OnCompletedOptions",
+ "type": "string",
+ "enum": ["responseHeaders"]
+ },
+ {
+ "id": "RequestFilter",
+ "type": "object",
+ "description": "An object describing filters to apply to webRequest events.",
+ "properties": {
+ "urls": {
+ "type": "array",
+ "description": "A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out.",
+ "items": { "type": "string" }
+ },
+ "types": {
+ "type": "array",
+ "optional": true,
+ "description": "A list of request types. Requests that cannot match any of the types will be filtered out.",
+ "items": { "$ref": "ResourceType" }
+ },
+ "tabId": { "type": "integer", "optional": true },
+ "windowId": { "type": "integer", "optional": true }
+ }
+ },
+ {
+ "id": "HttpHeaders",
+ "type": "array",
+ "description": "An array of HTTP headers. Each header is represented as a dictionary containing the keys <code>name</code> and either <code>value</code> or <code>binaryValue</code>.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "description": "Name of the HTTP header."},
+ "value": {"type": "string", "optional": true, "description": "Value of the HTTP header if it can be represented by UTF-8."},
+ "binaryValue": {
+ "type": "array",
+ "optional": true,
+ "description": "Value of the HTTP header if it cannot be represented by UTF-8, stored as individual byte values (0..255).",
+ "items": {"type": "integer"}
+ }
+ }
+ }
+ },
+ {
+ "id": "BlockingResponse",
+ "type": "object",
+ "description": "Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests.",
+ "properties": {
+ "cancel": {
+ "type": "boolean",
+ "optional": true,
+ "description": "If true, the request is cancelled. Used in onBeforeRequest, this prevents the request from being sent."
+ },
+ "redirectUrl": {
+ "type": "string",
+ "optional": true,
+ "description": "Only used as a response to the onBeforeRequest and onHeadersReceived events. If set, the original request is prevented from being sent/completed and is instead redirected to the given URL. Redirections to non-HTTP schemes such as data: are allowed. Redirects initiated by a redirect action use the original request method for the redirect, with one exception: If the redirect is initiated at the onHeadersReceived stage, then the redirect will be issued using the GET method."
+ },
+ "requestHeaders": {
+ "$ref": "HttpHeaders",
+ "optional": true,
+ "description": "Only used as a response to the onBeforeSendHeaders event. If set, the request is made with these request headers instead."
+ },
+ "responseHeaders": {
+ "$ref": "HttpHeaders",
+ "optional": true,
+ "description": "Only used as a response to the onHeadersReceived event. If set, the server is assumed to have responded with these response headers instead. Only return <code>responseHeaders</code> if you really want to modify the headers in order to limit the number of conflicts (only one extension may modify <code>responseHeaders</code> for each request)."
+ },
+ "authCredentials": {
+ "type": "object",
+ "description": "Only used as a response to the onAuthRequired event. If set, the request is made using the supplied credentials.",
+ "optional": true,
+ "properties": {
+ "username": {"type": "string"},
+ "password": {"type": "string"}
+ }
+ }
+ }
+ },
+ {
+ "id": "UploadData",
+ "type": "object",
+ "properties": {
+ "bytes": {
+ "type": "any",
+ "optional": true,
+ "description": "An ArrayBuffer with a copy of the data."
+ },
+ "file": {
+ "type": "string",
+ "optional": true,
+ "description": "A string with the file's path and name."
+ }
+ },
+ "description": "Contains data uploaded in a URL request."
+ }
+ ],
+ "functions": [
+ {
+ "name": "handlerBehaviorChanged",
+ "type": "function",
+ "description": "Needs to be called when the behavior of the webRequest handlers has changed to prevent incorrect handling due to caching. This function call is expensive. Don't call it often.",
+ "async": "callback",
+ "parameters": [
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "parameters": []
+ }
+ ]
+ }
+ ],
+ "events": [
+ {
+ "name": "onBeforeRequest",
+ "type": "function",
+ "description": "Fired when a request is about to occur.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "requestBody": {
+ "type": "object",
+ "optional": true,
+ "description": "Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'.",
+ "properties": {
+ "error": {"type": "string", "optional": true, "description": "Errors when obtaining request body data."},
+ "formData": {
+ "type": "object",
+ "optional": true,
+ "description": "If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}.",
+ "properties": {},
+ "additionalProperties": {
+ "type": "array",
+ "items": { "type": "string" }
+ }
+ },
+ "raw" : {
+ "type": "array",
+ "optional": true,
+ "items": {"$ref": "UploadData"},
+ "description": "If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array."
+ }
+ }
+ },
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnBeforeRequestOptions"
+ }
+ }
+ ],
+ "returns": {
+ "$ref": "BlockingResponse",
+ "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.",
+ "optional": true
+ }
+ },
+ {
+ "name": "onBeforeSendHeaders",
+ "type": "function",
+ "description": "Fired before sending an HTTP request, once the request headers are available. This may occur after a TCP connection is made to the server, but before any HTTP data is sent. ",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "requestHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP request headers that are going to be sent out with this request."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnBeforeSendHeadersOptions"
+ }
+ }
+ ],
+ "returns": {
+ "$ref": "BlockingResponse",
+ "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.",
+ "optional": true
+ }
+ },
+ {
+ "name": "onSendHeaders",
+ "type": "function",
+ "description": "Fired just before a request is going to be sent to the server (modifications of previous onBeforeSendHeaders callbacks are visible by the time onSendHeaders is fired).",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "requestHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP request headers that have been sent out with this request."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnSendHeadersOptions"
+ }
+ }
+ ]
+ },
+ {
+ "name": "onHeadersReceived",
+ "type": "function",
+ "description": "Fired when HTTP response headers of a request have been received.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line)."},
+ "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that have been received with this response."},
+ "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnHeadersReceivedOptions"
+ }
+ }
+ ],
+ "returns": {
+ "$ref": "BlockingResponse",
+ "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.",
+ "optional": true
+ }
+ },
+ {
+ "name": "onAuthRequired",
+ "unsupported": true,
+ "type": "function",
+ "description": "Fired when an authentication failure is received. The listener has three options: it can provide authentication credentials, it can cancel the request and display the error page, or it can take no action on the challenge. If bad user credentials are provided, this may be called multiple times for the same request.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "scheme": {"type": "string", "description": "The authentication scheme, e.g. Basic or Digest."},
+ "realm": {"type": "string", "description": "The authentication realm provided by the server, if there is one.", "optional": true},
+ "challenger": {"type": "object", "description": "The server requesting authentication.", "properties": {"host": {"type": "string"}, "port": {"type": "integer"}}},
+ "isProxy": {"type": "boolean", "description": "True for Proxy-Authenticate, false for WWW-Authenticate."},
+ "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."},
+ "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."},
+ "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."}
+ }
+ },
+ {
+ "type": "function",
+ "optional": true,
+ "name": "callback",
+ "parameters": [
+ {"name": "response", "$ref": "BlockingResponse"}
+ ]
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnAuthRequiredOptions"
+ }
+ }
+ ],
+ "returns": {
+ "$ref": "BlockingResponse",
+ "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.",
+ "optional": true
+ }
+ },
+ {
+ "name": "onResponseStarted",
+ "type": "function",
+ "description": "Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."},
+ "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."},
+ "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."},
+ "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."},
+ "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnResponseStartedOptions"
+ }
+ }
+ ]
+ },
+ {
+ "name": "onBeforeRedirect",
+ "type": "function",
+ "description": "Fired when a server-initiated redirect is about to occur.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."},
+ "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."},
+ "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."},
+ "redirectUrl": {"type": "string", "description": "The new URL."},
+ "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this redirect."},
+ "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnBeforeRedirectOptions"
+ }
+ }
+ ]
+ },
+ {
+ "name": "onCompleted",
+ "type": "function",
+ "description": "Fired when a request is completed.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."},
+ "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."},
+ "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."},
+ "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."},
+ "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ },
+ {
+ "type": "array",
+ "optional": true,
+ "name": "extraInfoSpec",
+ "description": "Array of extra information that should be passed to the listener function.",
+ "items": {
+ "$ref": "OnCompletedOptions"
+ }
+ }
+ ]
+ },
+ {
+ "name": "onErrorOccurred",
+ "type": "function",
+ "description": "Fired when an error occurs.",
+ "parameters": [
+ {
+ "type": "object",
+ "name": "details",
+ "properties": {
+ "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."},
+ "url": {"type": "string"},
+ "method": {"type": "string", "description": "Standard HTTP method."},
+ "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."},
+ "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."},
+ "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."},
+ "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."},
+ "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."},
+ "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."},
+ "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."},
+ "error": {"type": "string", "description": "The error description. This string is <em>not</em> guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content."}
+ }
+ }
+ ],
+ "extraParameters": [
+ {
+ "$ref": "RequestFilter",
+ "name": "filter",
+ "description": "A set of filters that restricts the events that will be sent to this listener."
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/toolkit/components/webextensions/test/mochitest/.eslintrc.js b/toolkit/components/webextensions/test/mochitest/.eslintrc.js
new file mode 100644
index 000000000..53938410b
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/.eslintrc.js
@@ -0,0 +1,35 @@
+"use strict";
+
+module.exports = { // eslint-disable-line no-undef
+ "extends": "../../../../../testing/mochitest/mochitest.eslintrc.js",
+
+ "env": {
+ "webextensions": true,
+ },
+
+ "globals": {
+ "ChromeWorker": false,
+ "onmessage": true,
+ "sendAsyncMessage": false,
+
+ "waitForLoad": true,
+ "promiseConsoleOutput": true,
+
+ "ExtensionTestUtils": false,
+ "NetUtil": true,
+ "webrequest_test": false,
+ "XPCOMUtils": true,
+
+ // head_webrequest.js symbols
+ "addStylesheet": true,
+ "addLink": true,
+ "addImage": true,
+ "addScript": true,
+ "addFrame": true,
+ "makeExtension": false,
+ },
+
+ "rules": {
+ "no-shadow": 0,
+ },
+};
diff --git a/toolkit/components/webextensions/test/mochitest/chrome.ini b/toolkit/components/webextensions/test/mochitest/chrome.ini
new file mode 100644
index 000000000..26585cad7
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/chrome.ini
@@ -0,0 +1,35 @@
+[DEFAULT]
+support-files =
+ chrome_head.js
+ head.js
+ head_cookies.js
+ file_sample.html
+ webrequest_chromeworker.js
+ webrequest_test.jsm
+tags = webextensions
+
+[test_chrome_ext_background_debug_global.html]
+skip-if = (os == 'android') # android doesn't have devtools
+[test_chrome_ext_background_page.html]
+skip-if = (toolkit == 'android') # android doesn't have devtools
+[test_chrome_ext_eventpage_warning.html]
+[test_chrome_ext_contentscript_unrecognizedprop_warning.html]
+skip-if = (os == 'android') # browser.tabs is undefined. Bug 1258975 on android.
+[test_chrome_ext_hybrid_addons.html]
+[test_chrome_ext_trustworthy_origin.html]
+[test_chrome_ext_webnavigation_resolved_urls.html]
+skip-if = (os == 'android') # browser.tabs is undefined. Bug 1258975 on android.
+[test_chrome_ext_shutdown_cleanup.html]
+[test_chrome_native_messaging_paths.html]
+skip-if = os != "mac" && os != "linux"
+[test_ext_cookies_expiry.html]
+[test_ext_cookies_permissions_bad.html]
+[test_ext_cookies_permissions_good.html]
+[test_ext_cookies_containers.html]
+[test_ext_jsversion.html]
+[test_ext_schema.html]
+[test_chrome_ext_storage_cleanup.html]
+[test_chrome_ext_idle.html]
+[test_chrome_ext_downloads_saveAs.html]
+[test_chrome_ext_webrequest_background_events.html]
+skip-if = os == 'android' # webrequest api unsupported (bug 1258975).
diff --git a/toolkit/components/webextensions/test/mochitest/chrome_head.js b/toolkit/components/webextensions/test/mochitest/chrome_head.js
new file mode 100644
index 000000000..da2f53a02
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/chrome_head.js
@@ -0,0 +1,12 @@
+"use strict";
+
+const {
+ classes: Cc,
+ interfaces: Ci,
+ utils: Cu,
+ results: Cr,
+} = Components;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/NetUtil.jsm");
+
diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html
new file mode 100644
index 000000000..663ebc611
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+<iframe src="file_WebNavigation_page2.html" width="200" height="200"></iframe>
+
+<form>
+</form>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html
new file mode 100644
index 000000000..cc1acc83d
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html
@@ -0,0 +1,7 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html
new file mode 100644
index 000000000..a0a26a2e9
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+<a id="elt" href="file_WebNavigation_page3.html#ref">click me</a>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html b/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html
new file mode 100644
index 000000000..5807dd439
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+<script>
+"use strict";
+window.close();
+</script>
+</head>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_csp.html b/toolkit/components/webextensions/test/mochitest/file_csp.html
new file mode 100644
index 000000000..206e44390
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_csp.html
@@ -0,0 +1,14 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+
+<div id="test">Sample text</div>
+<img id="bad-image" src="http://example.org/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png" />
+<script id="bad-script" type="text/javascript" src="http://example.org/tests/toolkit/components/extensions/test/mochitest/file_script_bad.js"></script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^ b/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^
new file mode 100644
index 000000000..4c6fa3c26
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^
@@ -0,0 +1 @@
+Content-Security-Policy: default-src 'self'
diff --git a/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js b/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js
new file mode 100644
index 000000000..06dfae65e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js
@@ -0,0 +1,12 @@
+"use strict";
+
+var {interfaces: Ci} = Components;
+
+Components.utils.import("resource://gre/modules/Services.jsm");
+
+Services.console.registerListener(function listener(message) {
+ if (/WebExt Privilege Escalation/.test(message.message)) {
+ Services.console.unregisterListener(listener);
+ sendAsyncMessage("console-message", {message: message.message});
+ }
+});
diff --git a/toolkit/components/webextensions/test/mochitest/file_image_bad.png b/toolkit/components/webextensions/test/mochitest/file_image_bad.png
new file mode 100644
index 000000000..4c3be5084
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_image_bad.png
Binary files differ
diff --git a/toolkit/components/webextensions/test/mochitest/file_image_good.png b/toolkit/components/webextensions/test/mochitest/file_image_good.png
new file mode 100644
index 000000000..769c63634
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_image_good.png
Binary files differ
diff --git a/toolkit/components/webextensions/test/mochitest/file_image_redirect.png b/toolkit/components/webextensions/test/mochitest/file_image_redirect.png
new file mode 100644
index 000000000..4c3be5084
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_image_redirect.png
Binary files differ
diff --git a/toolkit/components/webextensions/test/mochitest/file_mixed.html b/toolkit/components/webextensions/test/mochitest/file_mixed.html
new file mode 100644
index 000000000..f3c7dda58
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_mixed.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+
+<div id="test">Sample text</div>
+<img id="bad-image" src="http://example.com/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png" />
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html b/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html
new file mode 100644
index 000000000..22a55f90d
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html
@@ -0,0 +1,55 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+
+<script>
+"use strict";
+
+/* globals privilegedFetch, privilegedXHR */
+/* eslint-disable mozilla/balanced-listeners */
+
+addEventListener("message", function rcv(event) {
+ removeEventListener("message", rcv, false);
+
+ function assertTrue(condition, description) {
+ postMessage({msg: "assertTrue", condition, description}, "*");
+ }
+
+ function passListener() {
+ assertTrue(true, "Content XHR has no elevated privileges");
+ postMessage({"msg": "finish"}, "*");
+ }
+
+ function failListener() {
+ assertTrue(false, "Content XHR has no elevated privileges");
+ postMessage({"msg": "finish"}, "*");
+ }
+
+ try {
+ new privilegedXHR();
+ assertTrue(false, "Content should not have access to privileged XHR constructor");
+ } catch (e) {
+ assertTrue(/Permission denied to access object/.test(e), "Content should not have access to privileged XHR constructor");
+ }
+
+ try {
+ new privilegedFetch();
+ assertTrue(false, "Content should not have access to privileged fetch() constructor");
+ } catch (e) {
+ assertTrue(/Permission denied to access object/.test(e), "Content should not have access to privileged fetch() constructor");
+ }
+
+ let req = new XMLHttpRequest();
+ req.addEventListener("load", failListener);
+ req.addEventListener("error", passListener);
+ req.open("GET", "http://example.org/example.txt");
+ req.send();
+}, false);
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html b/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html
new file mode 100644
index 000000000..258f7058d
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+ <script type="text/javascript">
+ "use strict";
+ throw new Error(`WebExt Privilege Escalation: typeof(browser) = ${typeof(browser)}`);
+ </script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_sample.html b/toolkit/components/webextensions/test/mochitest/file_sample.html
new file mode 100644
index 000000000..a20e49a1f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_sample.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+
+<div id="test">Sample text</div>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_script_bad.js b/toolkit/components/webextensions/test/mochitest/file_script_bad.js
new file mode 100644
index 000000000..c425122c7
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_script_bad.js
@@ -0,0 +1,3 @@
+"use strict";
+
+window.failure = true;
diff --git a/toolkit/components/webextensions/test/mochitest/file_script_good.js b/toolkit/components/webextensions/test/mochitest/file_script_good.js
new file mode 100644
index 000000000..1848edf68
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_script_good.js
@@ -0,0 +1,3 @@
+"use strict";
+
+window.success = window.success ? window.success + 1 : 1;
diff --git a/toolkit/components/webextensions/test/mochitest/file_script_redirect.js b/toolkit/components/webextensions/test/mochitest/file_script_redirect.js
new file mode 100644
index 000000000..c89a196c2
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_script_redirect.js
@@ -0,0 +1,4 @@
+"use strict";
+
+window.failure = true;
+
diff --git a/toolkit/components/webextensions/test/mochitest/file_script_xhr.js b/toolkit/components/webextensions/test/mochitest/file_script_xhr.js
new file mode 100644
index 000000000..07f80eb2e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_script_xhr.js
@@ -0,0 +1,5 @@
+"use strict";
+
+var request = new XMLHttpRequest();
+request.open("get", "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/xhr_resource", false);
+request.send();
diff --git a/toolkit/components/webextensions/test/mochitest/file_style_bad.css b/toolkit/components/webextensions/test/mochitest/file_style_bad.css
new file mode 100644
index 000000000..8dbc8dc7a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_style_bad.css
@@ -0,0 +1,3 @@
+#test {
+ color: green !important;
+}
diff --git a/toolkit/components/webextensions/test/mochitest/file_style_good.css b/toolkit/components/webextensions/test/mochitest/file_style_good.css
new file mode 100644
index 000000000..46f9774b5
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_style_good.css
@@ -0,0 +1,3 @@
+#test {
+ color: red;
+}
diff --git a/toolkit/components/webextensions/test/mochitest/file_style_redirect.css b/toolkit/components/webextensions/test/mochitest/file_style_redirect.css
new file mode 100644
index 000000000..8dbc8dc7a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_style_redirect.css
@@ -0,0 +1,3 @@
+#test {
+ color: green !important;
+}
diff --git a/toolkit/components/webextensions/test/mochitest/file_teardown_test.js b/toolkit/components/webextensions/test/mochitest/file_teardown_test.js
new file mode 100644
index 000000000..7246012ad
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_teardown_test.js
@@ -0,0 +1,24 @@
+"use strict";
+
+/* globals addMessageListener */
+let {Management} = Components.utils.import("resource://gre/modules/Extension.jsm", {});
+let events = [];
+function record(type, extensionContext) {
+ let eventType = type == "proxy-context-load" ? "load" : "unload";
+ let url = extensionContext.uri.spec;
+ let extensionId = extensionContext.extension.id;
+ events.push({eventType, url, extensionId});
+}
+
+Management.on("proxy-context-load", record);
+Management.on("proxy-context-unload", record);
+addMessageListener("cleanup", () => {
+ Management.off("proxy-context-load", record);
+ Management.off("proxy-context-unload", record);
+});
+
+addMessageListener("get-context-events", extensionId => {
+ sendAsyncMessage("context-events", events);
+ events = [];
+});
+sendAsyncMessage("chromescript-startup");
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html
new file mode 100644
index 000000000..cba3043f7
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+
+<html>
+ <head>
+ <meta http-equiv="refresh" content="1;dummy_page.html">
+ </head>
+ <body>
+ </body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html
new file mode 100644
index 000000000..c5b436979
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html
@@ -0,0 +1,8 @@
+<!DOCTYPE HTML>
+
+<html>
+ <head>
+ </head>
+ <body>
+ </body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^
new file mode 100644
index 000000000..574a392a1
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^
@@ -0,0 +1 @@
+Refresh: 1;url=dummy_page.html
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html
new file mode 100644
index 000000000..d360bcbb1
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+<iframe src="file_webNavigation_clientRedirect.html" width="200" height="200"></iframe>
+
+<form>
+</form>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html
new file mode 100644
index 000000000..06dbd4374
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+<iframe src="redirection.sjs" width="200" height="200"></iframe>
+
+<form>
+</form>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html
new file mode 100644
index 000000000..307990714
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<body>
+
+<iframe src="file_webNavigation_manualSubframe_page1.html" width="200" height="200"></iframe>
+
+<form>
+</form>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html
new file mode 100644
index 000000000..55bb7aa6a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html
@@ -0,0 +1,8 @@
+<!DOCTYPE html>
+
+<html>
+ <body>
+ <h1>page1</h1>
+ <a href="file_webNavigation_manualSubframe_page2.html">page2</a>
+ </body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html
new file mode 100644
index 000000000..8f589f8bb
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html
@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+
+<html>
+ <body>
+ <h1>page2</h1>
+ </body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html b/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html
new file mode 100644
index 000000000..af51c2e52
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<head>
+ <meta charset="utf-8">
+</head>
+<body>
+ <iframe id="a_b" src="about:blank"></iframe>
+ <iframe srcdoc="galactica actual" src="adama"></iframe>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/head.js b/toolkit/components/webextensions/test/mochitest/head.js
new file mode 100644
index 000000000..1b1a29472
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/head.js
@@ -0,0 +1,13 @@
+"use strict";
+
+/* exported waitForLoad */
+
+function waitForLoad(win) {
+ return new Promise(resolve => {
+ win.addEventListener("load", function listener() {
+ win.removeEventListener("load", listener, true);
+ resolve();
+ }, true);
+ });
+}
+
diff --git a/toolkit/components/webextensions/test/mochitest/head_cookies.js b/toolkit/components/webextensions/test/mochitest/head_cookies.js
new file mode 100644
index 000000000..9f6966551
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/head_cookies.js
@@ -0,0 +1,167 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* exported testCookies */
+
+function* testCookies(options) {
+ // Changing the options object is a bit of a hack, but it allows us to easily
+ // pass an expiration date to the background script.
+ options.expiry = Date.now() / 1000 + 3600;
+
+ async function background(backgroundOptions) {
+ // Ask the parent scope to change some cookies we may or may not have
+ // permission for.
+ let awaitChanges = new Promise(resolve => {
+ browser.test.onMessage.addListener(msg => {
+ browser.test.assertEq("cookies-changed", msg, "browser.test.onMessage");
+ resolve();
+ });
+ });
+
+ let changed = [];
+ browser.cookies.onChanged.addListener(event => {
+ changed.push(`${event.cookie.name}:${event.cause}`);
+ });
+ browser.test.sendMessage("change-cookies");
+
+
+ // Try to access some cookies in various ways.
+ let {url, domain, secure} = backgroundOptions;
+
+ let failures = 0;
+ let tallyFailure = error => {
+ failures++;
+ };
+
+ try {
+ await awaitChanges;
+
+ let cookie = await browser.cookies.get({url, name: "foo"});
+ browser.test.assertEq(backgroundOptions.shouldPass, cookie != null, "should pass == get cookie");
+
+ let cookies = await browser.cookies.getAll({domain});
+ if (backgroundOptions.shouldPass) {
+ browser.test.assertEq(2, cookies.length, "expected number of cookies");
+ } else {
+ browser.test.assertEq(0, cookies.length, "expected number of cookies");
+ }
+
+ await Promise.all([
+ browser.cookies.set({url, domain, secure, name: "foo", "value": "baz", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
+ browser.cookies.set({url, domain, secure, name: "bar", "value": "quux", expirationDate: backgroundOptions.expiry}).catch(tallyFailure),
+ browser.cookies.remove({url, name: "deleted"}),
+ ]);
+
+ if (backgroundOptions.shouldPass) {
+ // The order of eviction events isn't guaranteed, so just check that
+ // it's there somewhere.
+ let evicted = changed.indexOf("evicted:evicted");
+ if (evicted < 0) {
+ browser.test.fail("got no eviction event");
+ } else {
+ browser.test.succeed("got eviction event");
+ changed.splice(evicted, 1);
+ }
+
+ browser.test.assertEq("x:explicit,x:overwrite,x:explicit,x:explicit,foo:overwrite,foo:explicit,bar:explicit,deleted:explicit",
+ changed.join(","), "expected changes");
+ } else {
+ browser.test.assertEq("", changed.join(","), "expected no changes");
+ }
+
+ if (!(backgroundOptions.shouldPass || backgroundOptions.shouldWrite)) {
+ browser.test.assertEq(2, failures, "Expected failures");
+ } else {
+ browser.test.assertEq(0, failures, "Expected no failures");
+ }
+
+ browser.test.notifyPass("cookie-permissions");
+ } catch (error) {
+ browser.test.fail(`Error: ${error} :: ${error.stack}`);
+ browser.test.notifyFail("cookie-permissions");
+ }
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "permissions": options.permissions,
+ },
+
+ background: `(${background})(${JSON.stringify(options)})`,
+ });
+
+
+ let cookieSvc = SpecialPowers.Services.cookies;
+
+ let domain = options.domain.replace(/^\.?/, ".");
+
+ // This will be evicted after we add a fourth cookie.
+ cookieSvc.add(domain, "/", "evicted", "bar", options.secure, false, false, options.expiry);
+ // This will be modified by the background script.
+ cookieSvc.add(domain, "/", "foo", "bar", options.secure, false, false, options.expiry);
+ // This will be deleted by the background script.
+ cookieSvc.add(domain, "/", "deleted", "bar", options.secure, false, false, options.expiry);
+
+
+ yield extension.startup();
+
+ yield extension.awaitMessage("change-cookies");
+ cookieSvc.add(domain, "/", "x", "y", options.secure, false, false, options.expiry);
+ cookieSvc.add(domain, "/", "x", "z", options.secure, false, false, options.expiry);
+ cookieSvc.remove(domain, "x", "/", false, {});
+ extension.sendMessage("cookies-changed");
+
+ yield extension.awaitFinish("cookie-permissions");
+ yield extension.unload();
+
+
+ function getCookies(host) {
+ let cookies = [];
+ let enum_ = cookieSvc.getCookiesFromHost(host, {});
+ while (enum_.hasMoreElements()) {
+ cookies.push(enum_.getNext().QueryInterface(SpecialPowers.Ci.nsICookie2));
+ }
+ return cookies.sort((a, b) => String.localeCompare(a.name, b.name));
+ }
+
+ let cookies = getCookies(options.domain);
+ info(`Cookies: ${cookies.map(c => `${c.name}=${c.value}`)}`);
+
+ if (options.shouldPass) {
+ is(cookies.length, 2, "expected two cookies for host");
+
+ is(cookies[0].name, "bar", "correct cookie name");
+ is(cookies[0].value, "quux", "correct cookie value");
+
+ is(cookies[1].name, "foo", "correct cookie name");
+ is(cookies[1].value, "baz", "correct cookie value");
+ } else if (options.shouldWrite) {
+ // Note: |shouldWrite| applies only when |shouldPass| is false.
+ // This is necessary because, unfortunately, websites (and therefore web
+ // extensions) are allowed to write some cookies which they're not allowed
+ // to read.
+ is(cookies.length, 3, "expected three cookies for host");
+
+ is(cookies[0].name, "bar", "correct cookie name");
+ is(cookies[0].value, "quux", "correct cookie value");
+
+ is(cookies[1].name, "deleted", "correct cookie name");
+
+ is(cookies[2].name, "foo", "correct cookie name");
+ is(cookies[2].value, "baz", "correct cookie value");
+ } else {
+ is(cookies.length, 2, "expected two cookies for host");
+
+ is(cookies[0].name, "deleted", "correct second cookie name");
+
+ is(cookies[1].name, "foo", "correct cookie name");
+ is(cookies[1].value, "bar", "correct cookie value");
+ }
+
+ for (let cookie of cookies) {
+ cookieSvc.remove(cookie.host, cookie.name, "/", false, {});
+ }
+ // Make sure we don't silently poison subsequent tests if something goes wrong.
+ is(getCookies(options.domain).length, 0, "cookies cleared");
+}
diff --git a/toolkit/components/webextensions/test/mochitest/head_webrequest.js b/toolkit/components/webextensions/test/mochitest/head_webrequest.js
new file mode 100644
index 000000000..96924e505
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/head_webrequest.js
@@ -0,0 +1,331 @@
+"use strict";
+
+let commonEvents = {
+ "onBeforeRequest": [{urls: ["<all_urls>"]}, ["blocking"]],
+ "onBeforeSendHeaders": [{urls: ["<all_urls>"]}, ["blocking", "requestHeaders"]],
+ "onSendHeaders": [{urls: ["<all_urls>"]}, ["requestHeaders"]],
+ "onBeforeRedirect": [{urls: ["<all_urls>"]}],
+ "onHeadersReceived": [{urls: ["<all_urls>"]}, ["blocking", "responseHeaders"]],
+ "onResponseStarted": [{urls: ["<all_urls>"]}],
+ "onCompleted": [{urls: ["<all_urls>"]}, ["responseHeaders"]],
+ "onErrorOccurred": [{urls: ["<all_urls>"]}],
+};
+
+function background(events) {
+ let expect;
+ let ignore;
+ let defaultOrigin;
+
+ browser.test.onMessage.addListener((msg, expected) => {
+ if (msg !== "set-expected") {
+ return;
+ }
+ expect = expected.expect;
+ defaultOrigin = expected.origin;
+ ignore = expected.ignore;
+ let promises = [];
+ // Initialize some stuff we'll need in the tests.
+ for (let entry of Object.values(expect)) {
+ // a place for the test infrastructure to store some state.
+ entry.test = {};
+ // Each entry in expected gets a Promise that will be resolved in the
+ // last event for that entry. This will either be onCompleted, or the
+ // last entry if an events list was provided.
+ promises.push(new Promise(resolve => { entry.test.resolve = resolve; }));
+ // If events was left undefined, we're expecting all normal events we're
+ // listening for, exclude onBeforeRedirect and onErrorOccurred
+ if (entry.events === undefined) {
+ entry.events = Object.keys(events).filter(name => name != "onErrorOccurred" && name != "onBeforeRedirect");
+ }
+ if (entry.optional_events === undefined) {
+ entry.optional_events = [];
+ }
+ }
+ // When every expected entry has finished our test is done.
+ Promise.all(promises).then(() => {
+ browser.test.sendMessage("done");
+ });
+ browser.test.sendMessage("continue");
+ });
+
+ // Retrieve the per-file/test expected values.
+ function getExpected(details) {
+ let url = new URL(details.url);
+ let filename;
+ if (url.protocol == "data:") {
+ // pathname is everything after protocol.
+ filename = url.pathname;
+ } else {
+ filename = url.pathname.split("/").pop();
+ }
+ if (ignore && ignore.includes(filename)) {
+ return;
+ }
+ let expected = expect[filename];
+ if (!expected) {
+ browser.test.fail(`unexpected request ${filename}`);
+ return;
+ }
+ // Save filename for redirect verification.
+ expected.test.filename = filename;
+ return expected;
+ }
+
+ // Process any test header modifications that can happen in request or response phases.
+ // If a test includes headers, it needs a complete header object, no undefined
+ // objects even if empty:
+ // request: {
+ // add: {"HeaderName": "value",},
+ // modify: {"HeaderName": "value",},
+ // remove: ["HeaderName",],
+ // },
+ // response: {
+ // add: {"HeaderName": "value",},
+ // modify: {"HeaderName": "value",},
+ // remove: ["HeaderName",],
+ // },
+ function processHeaders(phase, expected, details) {
+ // This should only happen once per phase [request|response].
+ browser.test.assertFalse(!!expected.test[phase], `First processing of headers for ${phase}`);
+ expected.test[phase] = true;
+
+ let headers = details[`${phase}Headers`];
+ browser.test.assertTrue(Array.isArray(headers), `${phase}Headers array present`);
+
+ let {add, modify, remove} = expected.headers[phase];
+
+ for (let name in add) {
+ browser.test.assertTrue(!headers.find(h => h.name === name), `header ${name} to be added not present yet in ${phase}Headers`);
+ let header = {name: name};
+ if (name.endsWith("-binary")) {
+ header.binaryValue = Array.from(add[name], c => c.charCodeAt(0));
+ } else {
+ header.value = add[name];
+ }
+ headers.push(header);
+ }
+
+ let modifiedAny = false;
+ for (let header of headers) {
+ if (header.name.toLowerCase() in modify) {
+ header.value = modify[header.name.toLowerCase()];
+ modifiedAny = true;
+ }
+ }
+ browser.test.assertTrue(modifiedAny, `at least one ${phase}Headers element to modify`);
+
+ let deletedAny = false;
+ for (let j = headers.length; j-- > 0;) {
+ if (remove.includes(headers[j].name.toLowerCase())) {
+ headers.splice(j, 1);
+ deletedAny = true;
+ }
+ }
+ browser.test.assertTrue(deletedAny, `at least one ${phase}Headers element to delete`);
+
+ return headers;
+ }
+
+ // phase is request or response.
+ function checkHeaders(phase, expected, details) {
+ if (!/^https?:/.test(details.url)) {
+ return;
+ }
+
+ let headers = details[`${phase}Headers`];
+ browser.test.assertTrue(Array.isArray(headers), `valid ${phase}Headers array`);
+
+ let {add, modify, remove} = expected.headers[phase];
+ for (let name in add) {
+ let value = headers.find(h => h.name.toLowerCase() === name.toLowerCase()).value;
+ browser.test.assertEq(value, add[name], `header ${name} correctly injected in ${phase}Headers`);
+ }
+
+ for (let name in modify) {
+ let value = headers.find(h => h.name.toLowerCase() === name.toLowerCase()).value;
+ browser.test.assertEq(value, modify[name], `header ${name} matches modified value`);
+ }
+
+ for (let name of remove) {
+ let found = headers.find(h => h.name.toLowerCase() === name.toLowerCase());
+ browser.test.assertFalse(!!found, `deleted header ${name} still found in ${phase}Headers`);
+ }
+ }
+
+ function getListener(name) {
+ return details => {
+ let result = {};
+ browser.test.log(`${name} ${details.requestId} ${details.url}`);
+ let expected = getExpected(details);
+ if (!expected) {
+ return result;
+ }
+ let expectedEvent = expected.events[0] == name;
+ if (expectedEvent) {
+ expected.events.shift();
+ } else {
+ expectedEvent = expected.optional_events[0] == name;
+ if (expectedEvent) {
+ expected.optional_events.shift();
+ }
+ }
+ browser.test.assertTrue(expectedEvent, `received ${name}`);
+ browser.test.assertEq(expected.type, details.type, "resource type is correct");
+ browser.test.assertEq(expected.origin || defaultOrigin, details.originUrl, "origin is correct");
+
+ if (name == "onBeforeRequest") {
+ // Save some values to test request consistency in later events.
+ browser.test.assertTrue(details.tabId !== undefined, `tabId ${details.tabId}`);
+ browser.test.assertTrue(details.requestId !== undefined, `requestId ${details.requestId}`);
+ // Validate requestId if it's already set, this happens with redirects.
+ if (expected.test.requestId !== undefined) {
+ browser.test.assertEq("string", typeof expected.test.requestId, `requestid ${expected.test.requestId} is string`);
+ browser.test.assertEq("string", typeof details.requestId, `requestid ${details.requestId} is string`);
+ browser.test.assertEq("number", typeof parseInt(details.requestId, 10), "parsed requestid is number");
+ browser.test.assertNotEq(expected.test.requestId, details.requestId,
+ `last requestId ${expected.test.requestId} different from this one ${details.requestId}`);
+ } else {
+ // Save any values we want to validate in later events.
+ expected.test.requestId = details.requestId;
+ expected.test.tabId = details.tabId;
+ }
+ // Tests we don't need to do every event.
+ browser.test.assertTrue(details.type.toUpperCase() in browser.webRequest.ResourceType, `valid resource type ${details.type}`);
+ if (details.type == "main_frame") {
+ browser.test.assertEq(0, details.frameId, "frameId is zero when type is main_frame bug 1329299");
+ }
+ } else {
+ // On events after onBeforeRequest, check the previous values.
+ browser.test.assertEq(expected.test.requestId, details.requestId, "correct requestId");
+ browser.test.assertEq(expected.test.tabId, details.tabId, "correct tabId");
+ }
+ if (name == "onBeforeSendHeaders") {
+ if (expected.headers && expected.headers.request) {
+ result.requestHeaders = processHeaders("request", expected, details);
+ }
+ if (expected.redirect) {
+ browser.test.log(`${name} redirect request`);
+ result.redirectUrl = details.url.replace(expected.test.filename, expected.redirect);
+ }
+ }
+ if (name == "onSendHeaders") {
+ if (expected.headers && expected.headers.request) {
+ checkHeaders("request", expected, details);
+ }
+ }
+ if (name == "onHeadersReceived") {
+ browser.test.assertEq(expected.status || 200, details.statusCode,
+ `expected HTTP status received for ${details.url}`);
+ if (expected.headers && expected.headers.response) {
+ result.responseHeaders = processHeaders("response", expected, details);
+ }
+ }
+ if (name == "onCompleted") {
+ // If we have already completed a GET request for this url,
+ // and it was found, we expect for the response to come fromCache.
+ // expected.cached may be undefined, force boolean.
+ let expectCached = !!expected.cached && details.method === "GET" && details.statusCode != 404;
+ browser.test.assertEq(expectCached, details.fromCache, "fromCache is correct");
+ // We can only tell IPs for non-cached HTTP requests.
+ if (!details.fromCache && /^https?:/.test(details.url)) {
+ browser.test.assertEq("127.0.0.1", details.ip, `correct ip for ${details.url}`);
+ }
+ if (expected.headers && expected.headers.response) {
+ checkHeaders("response", expected, details);
+ }
+ }
+
+ if (expected.cancel && expected.cancel == name) {
+ browser.test.log(`${name} cancel request`);
+ browser.test.sendMessage("cancelled");
+ result.cancel = true;
+ }
+ // If we've used up all the events for this test, resolve the promise.
+ // If something wrong happens and more events come through, there will be
+ // failures.
+ if (expected.events.length <= 0) {
+ expected.test.resolve();
+ }
+ return result;
+ };
+ }
+
+ for (let [name, args] of Object.entries(events)) {
+ browser.test.log(`adding listener for ${name}`);
+ try {
+ browser.webRequest[name].addListener(getListener(name), ...args);
+ } catch (e) {
+ browser.test.assertTrue(/\brequestBody\b/.test(e.message),
+ "Request body is unsupported");
+
+ // RequestBody is disabled in release builds.
+ if (!/\brequestBody\b/.test(e.message)) {
+ throw e;
+ }
+
+ args.splice(args.indexOf("requestBody"), 1);
+ browser.webRequest[name].addListener(getListener(name), ...args);
+ }
+ }
+}
+
+/* exported makeExtension */
+
+function makeExtension(events = commonEvents) {
+ return ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "webRequestBlocking",
+ "<all_urls>",
+ ],
+ },
+ background: `(${background})(${JSON.stringify(events)})`,
+ });
+}
+
+/* exported addStylesheet */
+
+function addStylesheet(file) {
+ let link = document.createElement("link");
+ link.setAttribute("rel", "stylesheet");
+ link.setAttribute("href", file);
+ document.body.appendChild(link);
+}
+
+/* exported addLink */
+
+function addLink(file) {
+ let a = document.createElement("a");
+ a.setAttribute("href", file);
+ a.setAttribute("target", "_blank");
+ document.body.appendChild(a);
+ return a;
+}
+
+/* exported addImage */
+
+function addImage(file) {
+ let img = document.createElement("img");
+ img.setAttribute("src", file);
+ document.body.appendChild(img);
+}
+
+/* exported addScript */
+
+function addScript(file) {
+ let script = document.createElement("script");
+ script.setAttribute("type", "text/javascript");
+ script.setAttribute("src", file);
+ document.getElementsByTagName("head").item(0).appendChild(script);
+}
+
+/* exported addFrame */
+
+function addFrame(file) {
+ let frame = document.createElement("iframe");
+ frame.setAttribute("width", "200");
+ frame.setAttribute("height", "200");
+ frame.setAttribute("src", file);
+ document.body.appendChild(frame);
+}
diff --git a/toolkit/components/webextensions/test/mochitest/mochitest.ini b/toolkit/components/webextensions/test/mochitest/mochitest.ini
new file mode 100644
index 000000000..45586237e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/mochitest.ini
@@ -0,0 +1,114 @@
+[DEFAULT]
+support-files =
+ head.js
+ file_mixed.html
+ head_webrequest.js
+ file_csp.html
+ file_csp.html^headers^
+ file_WebRequest_page3.html
+ file_webNavigation_clientRedirect.html
+ file_webNavigation_clientRedirect_httpHeaders.html
+ file_webNavigation_clientRedirect_httpHeaders.html^headers^
+ file_webNavigation_frameClientRedirect.html
+ file_webNavigation_frameRedirect.html
+ file_webNavigation_manualSubframe.html
+ file_webNavigation_manualSubframe_page1.html
+ file_webNavigation_manualSubframe_page2.html
+ file_WebNavigation_page1.html
+ file_WebNavigation_page2.html
+ file_WebNavigation_page3.html
+ file_with_about_blank.html
+ file_image_good.png
+ file_image_bad.png
+ file_image_redirect.png
+ file_style_good.css
+ file_style_bad.css
+ file_style_redirect.css
+ file_script_good.js
+ file_script_bad.js
+ file_script_redirect.js
+ file_script_xhr.js
+ file_sample.html
+ redirection.sjs
+ file_privilege_escalation.html
+ file_ext_test_api_injection.js
+ file_permission_xhr.html
+ file_teardown_test.js
+ return_headers.sjs
+ webrequest_worker.js
+tags = webextensions
+
+[test_clipboard.html]
+# skip-if = # disabled test case with_permission_allow_copy, see inline comment.
+[test_ext_inIncognitoContext_window.html]
+skip-if = os == 'android' # Android does not currently support windows.
+[test_ext_geturl.html]
+[test_ext_background_canvas.html]
+[test_ext_content_security_policy.html]
+[test_ext_contentscript.html]
+[test_ext_contentscript_api_injection.html]
+[test_ext_contentscript_async_loading.html]
+[test_ext_contentscript_context.html]
+[test_ext_contentscript_create_iframe.html]
+[test_ext_contentscript_devtools_metadata.html]
+[test_ext_contentscript_exporthelpers.html]
+[test_ext_contentscript_css.html]
+[test_ext_contentscript_about_blank.html]
+[test_ext_contentscript_permission.html]
+skip-if = os == 'android' # Android does not support tabs API. Bug 1260250
+[test_ext_contentscript_teardown.html]
+skip-if = (os == 'android') # Android does not support tabs API. Bug 1260250
+[test_ext_exclude_include_globs.html]
+[test_ext_i18n_css.html]
+[test_ext_generate.html]
+[test_ext_notifications.html]
+[test_ext_permission_xhr.html]
+[test_ext_runtime_connect.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_runtime_connect_twoway.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_runtime_connect2.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_runtime_disconnect.html]
+[test_ext_runtime_id.html]
+[test_ext_sandbox_var.html]
+[test_ext_sendmessage_reply.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_sendmessage_reply2.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_sendmessage_doublereply.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_sendmessage_no_receiver.html]
+[test_ext_storage_content.html]
+[test_ext_storage_tab.html]
+skip-if = os == 'android' # Android does not currently support tabs.
+[test_ext_test.html]
+[test_ext_cookies.html]
+skip-if = os == 'android' # Bug 1258975 on android.
+[test_ext_background_api_injection.html]
+[test_ext_background_generated_url.html]
+[test_ext_background_teardown.html]
+[test_ext_tab_teardown.html]
+skip-if = (os == 'android') # Android does not support tabs API. Bug 1260250
+[test_ext_unload_frame.html]
+[test_ext_i18n.html]
+skip-if = (os == 'android') # Bug 1258975 on android.
+[test_ext_listener_proxies.html]
+[test_ext_web_accessible_resources.html]
+skip-if = (os == 'android') # Bug 1258975 on android.
+[test_ext_webrequest_background_events.html]
+skip-if = os == 'android' # webrequest api unsupported (bug 1258975).
+[test_ext_webrequest_basic.html]
+skip-if = os == 'android' # webrequest api unsupported (bug 1258975).
+[test_ext_webrequest_suspend.html]
+skip-if = os == 'android' # webrequest api unsupported (bug 1258975).
+[test_ext_webrequest_upload.html]
+skip-if = release_or_beta || os == 'android' # webrequest api unsupported (bug 1258975).
+[test_ext_webnavigation.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_webnavigation_filters.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_window_postMessage.html]
+[test_ext_subframes_privileges.html]
+skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975).
+[test_ext_xhr_capabilities.html]
diff --git a/toolkit/components/webextensions/test/mochitest/redirection.sjs b/toolkit/components/webextensions/test/mochitest/redirection.sjs
new file mode 100644
index 000000000..370ecd213
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/redirection.sjs
@@ -0,0 +1,4 @@
+function handleRequest(aRequest, aResponse) {
+ aResponse.setStatusLine(aRequest.httpVersion, 302);
+ aResponse.setHeader("Location", "./dummy_page.html");
+}
diff --git a/toolkit/components/webextensions/test/mochitest/return_headers.sjs b/toolkit/components/webextensions/test/mochitest/return_headers.sjs
new file mode 100644
index 000000000..54e2e5fb4
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/return_headers.sjs
@@ -0,0 +1,20 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set ft=javascript sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* exported handleRequest */
+
+function handleRequest(request, response) {
+ response.setHeader("Content-Type", "text/plain", false);
+
+ let headers = {};
+ // Why on earth is this a nsISimpleEnumerator...
+ let enumerator = request.headers;
+ while (enumerator.hasMoreElements()) {
+ let header = enumerator.getNext().data;
+ headers[header.toLowerCase()] = request.getHeader(header);
+ }
+
+ response.write(JSON.stringify(headers));
+}
+
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html
new file mode 100644
index 000000000..0edf5ea86
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html
@@ -0,0 +1,166 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm");
+Cu.import("resource://gre/modules/AddonManager.jsm");
+
+const {
+ XPIProvider,
+} = Components.utils.import("resource://gre/modules/addons/XPIProvider.jsm");
+
+/**
+ * This test is asserting that ext-backgroundPage.js successfully sets its
+ * debug global in the AddonWrapper provided by XPIProvider.jsm
+ *
+ * It does _not_ test any functionality in devtools and does not guarantee
+ * debugging is actually working correctly end-to-end.
+ */
+
+function background() {
+ window.testThing = "test!";
+ browser.test.notifyPass("background script ran");
+}
+
+const ID = "debug@tests.mozilla.org";
+let extensionData = {
+ useAddonManager: "temporary",
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ },
+};
+
+add_task(function* () {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("background script ran");
+
+ yield new Promise(function(resolve) {
+ window.BrowserToolboxProcess.emit("connectionchange", "opened", {
+ setAddonOptions(id, options) {
+ if (id === ID) {
+ let context = Cu.waiveXrays(options.global);
+ ok(context.chrome, "global context has a chrome object");
+ ok(context.browser, "global context has a browser object");
+ is("test!", context.testThing, "global context is the background script context");
+ resolve();
+ }
+ },
+ });
+ });
+
+ let addon = yield new Promise((resolve, reject) => {
+ AddonManager.getAddonByID(ID, addon => addon ? resolve(addon) : reject());
+ });
+
+ ok(addon, `Got the addon wrapper for ${addon.id}`);
+
+ function waitForDebugGlobalChanges(times, initialAddonInstanceID) {
+ return new Promise((resolve) => {
+ AddonManager.addAddonListener({
+ count: 0,
+ notNullGlobalsCount: 0,
+ undefinedPrivateWrappersCount: 0,
+ lastAddonInstanceID: initialAddonInstanceID,
+ onPropertyChanged(newAddon, changedPropNames) {
+ if (newAddon.id != addon.id ||
+ !changedPropNames.includes("debugGlobal")) {
+ return;
+ }
+
+ ok(!(newAddon.setDebugGlobal) && !(newAddon.getDebugGlobal),
+ "The addon wrapper should not be a PrivateWrapper");
+
+ let activeAddon = XPIProvider.activeAddons.get(addon.id);
+
+ let addonInstanceID;
+
+ if (!activeAddon) {
+ // The addon has been disable, the preferred global should be null
+ addonInstanceID = this.lastAddonInstanceID;
+ delete this.lastAddonInstanceID;
+ } else {
+ addonInstanceID = activeAddon.instanceID;
+ this.lastAddonInstanceID = addonInstanceID;
+ }
+
+ ok(addonInstanceID, `Got the addon instanceID for ${addon.id}`);
+
+ AddonManager.getAddonByInstanceID(addonInstanceID).then((privateWrapper) => {
+ this.count += 1;
+
+ if (!privateWrapper) {
+ // The addon has been uninstalled
+ this.undefinedPrivateWrappersCount += 1;
+ } else {
+ ok((privateWrapper.getDebugGlobal), "Got the addon PrivateWrapper");
+
+ if (privateWrapper.getDebugGlobal()) {
+ this.notNullGlobalsCount += 1;
+ }
+ }
+
+ if (this.count == times) {
+ AddonManager.removeAddonListener(this);
+ resolve({
+ counters: {
+ count: this.count,
+ notNullGlobalsCount: this.notNullGlobalsCount,
+ undefinedPrivateWrappersCount: this.undefinedPrivateWrappersCount,
+ },
+ lastAddonInstanceID: this.lastAddonInstanceID,
+ });
+ }
+ });
+ },
+ });
+ });
+ }
+
+ // two calls expected, one for the shutdown and one for the startup
+ // of the background page.
+ let waitForDebugGlobalChangesOnReload = waitForDebugGlobalChanges(2);
+
+ info("Addon reload...");
+ yield addon.reload();
+
+ info("Addon completed startup after reload");
+
+ let {
+ counters: reloadCounters,
+ lastAddonInstanceID,
+ } = yield waitForDebugGlobalChangesOnReload;
+
+ isDeeply(reloadCounters, {count: 2, notNullGlobalsCount: 1, undefinedPrivateWrappersCount: 0},
+ "Got the expected number of onPropertyChanged calls on reload");
+
+ // one more call expected for the shutdown.
+ let waitForDebugGlobalChangesOnShutdown = waitForDebugGlobalChanges(1, lastAddonInstanceID);
+
+ info("extension unloading...");
+ yield extension.unload();
+ info("extension unloaded");
+
+ let {counters: unloadCounters} = yield waitForDebugGlobalChangesOnShutdown;
+
+ isDeeply(unloadCounters, {count: 1, notNullGlobalsCount: 0, undefinedPrivateWrappersCount: 1},
+ "Got the expected number of onPropertyChanged calls on shutdown");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html
new file mode 100644
index 000000000..3c4774652
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html
@@ -0,0 +1,84 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+Cu.import("resource://testing-common/TestUtils.jsm");
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* testAlertNotShownInBackgroundWindow() {
+ ok(!Services.wm.getEnumerator("alert:alert").hasMoreElements(),
+ "Alerts should not be present at the start of the test.");
+
+ let consoleOpened = TestUtils.topicObserved("web-console-created");
+
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: function() {
+ browser.test.log("background script executed");
+
+ alert("I am an alert in the background.");
+
+ browser.test.notifyPass("alertCalled");
+ },
+ });
+
+ yield extension.startup();
+
+ info("startup complete loaded");
+
+ yield extension.awaitFinish("alertCalled");
+
+
+ let alertWindows = Services.wm.getEnumerator("alert:alert");
+ ok(!alertWindows.hasMoreElements(), "Should not show alert");
+
+
+ // Make sure the message we output to the console is seen.
+ // This message is in ext-backgroundPage.js
+ let events = Cc["@mozilla.org/consoleAPI-storage;1"]
+ .getService(Ci.nsIConsoleAPIStorage).getEvents();
+
+ // This is the warning that is output after the first `alert()` call is made.
+ let alertWarningEvent = events[events.length - 2];
+ is(alertWarningEvent.arguments[0], "alert() is not supported in background windows; please use console.log instead.");
+
+ // This is the actual alert text that should be present in the console
+ // instead of as an `alert`.
+ let alertEvent = events[events.length - 1];
+ is(alertEvent.arguments[0], "I am an alert in the background.");
+
+
+ // Wait for the browser console window to open.
+ yield consoleOpened;
+
+ let {require} = Cu.import("resource://devtools/shared/Loader.jsm", {});
+ require("devtools/client/framework/devtools-browser");
+ let hudservice = require("devtools/client/webconsole/hudservice");
+
+ // And then double check that we have an actual browser console.
+ let haveConsole = !!hudservice.getBrowserConsole();
+ ok(haveConsole, "Expected browser console to be open");
+
+ if (haveConsole) {
+ yield hudservice.toggleBrowserConsole();
+ }
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html
new file mode 100644
index 000000000..e08121a8f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html
@@ -0,0 +1,80 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script unrecognized property on manifest</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+const BASE = "http://mochi.test:8888/chrome/toolkit/components/extensions/test/mochitest";
+
+add_task(function* test_contentscript() {
+ function background() {
+ browser.runtime.onMessage.addListener(async (msg) => {
+ if (msg == "loaded") {
+ // NOTE: we're removing the tab from here because doing a win.close()
+ // from the chrome test code is raising a "TypeError: can't access
+ // dead object" exception.
+ let tabs = await browser.tabs.query({active: true, currentWindow: true});
+ await browser.tabs.remove(tabs[0].id);
+
+ browser.test.notifyPass("content-script-loaded");
+ }
+ });
+ }
+
+ function contentScript() {
+ chrome.runtime.sendMessage("loaded");
+ }
+
+ let extensionData = {
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ "unrecognized_property": "with-a-random-value",
+ },
+ ],
+ },
+ background,
+
+ files: {
+ "content_script.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ SimpleTest.waitForExplicitFinish();
+ let waitForConsole = new Promise(resolve => {
+ SimpleTest.monitorConsole(resolve, [{
+ message: /Reading manifest: Error processing content_scripts.*.unrecognized_property: An unexpected property was found/,
+ }]);
+ });
+
+ yield extension.startup();
+
+ window.open(`${BASE}/file_sample.html`);
+
+ yield Promise.all([extension.awaitFinish("content-script-loaded")]);
+ info("test page loaded");
+
+ yield extension.unload();
+
+ SimpleTest.endMonitorConsole();
+ yield waitForConsole;
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html
new file mode 100644
index 000000000..c1aaae035
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html
@@ -0,0 +1,68 @@
+<!doctype html>
+<html>
+<head>
+ <title>Test downloads.download() saveAs option</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_downloads_saveAs() {
+ function background() {
+ const url = URL.createObjectURL(new Blob(["file content"]));
+ browser.test.onMessage.addListener(async () => {
+ try {
+ let id = await browser.downloads.download({url, saveAs: true});
+ browser.downloads.onChanged.addListener(delta => {
+ if (delta.state.current === "complete") {
+ browser.test.sendMessage("done", {ok: true, id});
+ }
+ });
+ } catch ({message}) {
+ browser.test.sendMessage("done", {ok: false, message});
+ }
+ });
+ browser.test.sendMessage("ready");
+ }
+
+ const {MockFilePicker} = SpecialPowers;
+ const manifest = {background, manifest: {permissions: ["downloads"]}};
+ const extension = ExtensionTestUtils.loadExtension(manifest);
+
+ MockFilePicker.init(window);
+ MockFilePicker.useAnyFile();
+ const [file] = MockFilePicker.returnFiles;
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage("download");
+ let result = yield extension.awaitMessage("done");
+
+ ok(result.ok, "downloads.download() works with saveAs");
+ is(file.fileSize, 12, "downloaded file is the correct size");
+ file.remove(false);
+
+ // Test the user canceling the save dialog.
+ MockFilePicker.returnValue = MockFilePicker.returnCancel;
+
+ extension.sendMessage("download");
+ result = yield extension.awaitMessage("done");
+
+ ok(!result.ok, "download rejected if the user cancels the dialog");
+ is(result.message, "Download canceled by the user", "with the correct message");
+ ok(!file.exists(), "file was not downloaded");
+
+ yield extension.unload();
+ MockFilePicker.cleanup();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html
new file mode 100644
index 000000000..ecea8237e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html
@@ -0,0 +1,106 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for WebExtension EventPage Warning</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function createEventPageExtension(eventPage) {
+ function eventPageScript() {
+ browser.test.log("running event page as background script");
+ browser.test.sendMessage("running", 1);
+ }
+
+ return ExtensionTestUtils.loadExtension({
+ manifest: {
+ "background": eventPage,
+ },
+ files: {
+ "event-page-script.js": eventPageScript,
+ "event-page.html": `<html><head>
+ <meta charset="utf-8">
+ <script src="event-page-script.js"><\/script>
+ </head></html>`,
+ },
+ });
+}
+
+add_task(function* test_eventpages() {
+ // Used in other tests to prevent the monitorConsole to grip.
+ SimpleTest.waitForExplicitFinish();
+
+ let testCases = [
+ {
+ message: "testing event page running as a background page",
+ eventPage: {
+ "page": "event-page.html",
+ "persistent": false,
+ },
+ },
+ {
+ message: "testing event page scripts running as a background page",
+ eventPage: {
+ "scripts": ["event-page-script.js"],
+ "persistent": false,
+ },
+ },
+ ];
+
+ for (let {message, eventPage} of testCases) {
+ info(message);
+
+ // Wait for the expected logged warnings from the manifest validation.
+ let waitForConsole = new Promise(resolve => {
+ SimpleTest.monitorConsole(resolve, [{message: /Event pages are not currently supported./}]);
+ });
+
+ let extension = createEventPageExtension(eventPage);
+
+ info("load complete");
+ let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
+ is(x, 1, "got correct value from extension");
+ info("test complete");
+ yield extension.unload();
+ info("extension unloaded successfully");
+
+ SimpleTest.endMonitorConsole();
+ yield waitForConsole;
+
+ waitForConsole = new Promise(resolve => {
+ SimpleTest.monitorConsole(resolve, [{
+ message: /Reading manifest: Error processing background.nonExistentProp: An unexpected property was found/,
+ }]);
+ });
+
+ info("testing additional unrecognized properties on background page");
+
+ extension = createEventPageExtension({
+ "scripts": ["event-page-script.js"],
+ "nonExistentProp": true,
+ });
+
+ info("load complete");
+ [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
+ is(x, 1, "got correct value from extension");
+ info("test complete");
+ yield extension.unload();
+ info("extension unloaded successfully");
+
+ SimpleTest.endMonitorConsole();
+ yield waitForConsole;
+ }
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html
new file mode 100644
index 000000000..a74c551f0
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html
@@ -0,0 +1,141 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for hybrid addons: SDK or bootstrap.js + embedded WebExtension</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/**
+ * This test contains additional tests that ensure that an SDK hybrid addon
+ * which is using the new module loader can embed a webextension correctly:
+ *
+ * while the other tests related to the "Embedded WebExtension" are focused
+ * on unit testing a specific component, these tests are testing that a complete
+ * hybrid SDK addon works as expected.
+ *
+ * NOTE: this tests are also the only ones which tests an SDK hybrid addon that
+ * uses the new module loader (the one actually used in production by real world
+ * addons these days), while the Addon SDK "embedded-webextension" test addon
+ * uses the old deprecated module loader (as all the other Addon SDK test addons).
+ */
+
+function generateClassicExtensionFiles({id, files}) {
+ // The addon install.rdf file, as it would be generated by jpm from the addon
+ // package.json metadata.
+ files["install.rdf"] = `<?xml version="1.0" encoding="utf-8"?>
+ <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+ <Description about="urn:mozilla:install-manifest">
+ <em:id>${id}</em:id>
+ <em:type>2</em:type>
+ <em:bootstrap>true</em:bootstrap>
+ <em:hasEmbeddedWebExtension>true</em:hasEmbeddedWebExtension>
+ <em:unpack>false</em:unpack>
+ <em:version>0.1.0</em:version>
+ <em:name>Fake Hybrid Addon</em:name>
+ <em:description>A fake hybrid addon</em:description>
+
+ <!-- Firefox -->
+ <em:targetApplication>
+ <Description>
+ <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
+ <em:minVersion>51.0a1</em:minVersion>
+ <em:maxVersion>*</em:maxVersion>
+ </Description>
+ </em:targetApplication>
+
+ <!-- Fennec -->
+ <em:targetApplication>
+ <Description>
+ <em:id>{aa3c5121-dab2-40e2-81ca-7ea25febc110}</em:id>
+ <em:minVersion>51.0a1</em:minVersion>
+ <em:maxVersion>*</em:maxVersion>
+ </Description>
+ </em:targetApplication>
+ </Description>
+ </RDF>`;
+
+ // The addon package.json file.
+ files["package.json"] = `{
+ "id": "${id}",
+ "name": "hybrid-addon",
+ "version": "0.1.0",
+ "description": "A fake hybrid addon",
+ "main": "index.js",
+ "engines": {
+ "firefox": ">= 51.0a1",
+ "fennec": ">= 51.0a1"
+ },
+ "license": "MPL-2.0",
+ "hasEmbeddedWebExtension": true
+ }`;
+
+ // The bootstrap file that jpm bundle in any SDK addon built with it.
+ files["bootstrap.js"] = `
+ const { utils: Cu } = Components;
+ const rootURI = __SCRIPT_URI_SPEC__.replace("bootstrap.js", "");
+ const COMMONJS_URI = "resource://gre/modules/commonjs";
+ const { require } = Cu.import(COMMONJS_URI + "/toolkit/require.js", {});
+ const { Bootstrap } = require(COMMONJS_URI + "/sdk/addon/bootstrap.js");
+ var { startup, shutdown, install, uninstall } = new Bootstrap(rootURI);
+ `;
+
+ return files;
+}
+
+add_task(function* test_sdk_hybrid_addon_with_jpm_module_loader() {
+ function backgroundScript() {
+ browser.runtime.sendMessage("background message", (reply) => {
+ browser.test.assertEq("sdk received message: background message", reply,
+ "Got the expected reply from the SDK context");
+ browser.test.notifyPass("sdk.webext-api.onmessage");
+ });
+ }
+
+ async function sdkMainScript() {
+ /* globals require */
+ const webext = require("sdk/webextension");
+ let {browser} = await webext.startup();
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ sendReply(`sdk received message: ${msg}`);
+ });
+ }
+
+ let id = "fake@sdk.hybrid.addon";
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "temporary",
+ files: generateClassicExtensionFiles({
+ id,
+ files: {
+ "index.js": sdkMainScript,
+ "webextension/manifest.json": {
+ name: "embedded webextension name",
+ manifest_version: 2,
+ version: "0.1.0",
+ background: {
+ scripts: ["bg.js"],
+ },
+ },
+ "webextension/bg.js": backgroundScript,
+ },
+ }),
+ }, id);
+
+ extension.startup();
+
+ yield extension.awaitFinish("sdk.webext-api.onmessage");
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html
new file mode 100644
index 000000000..3c3063e67
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html
@@ -0,0 +1,64 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+const idleService = Cc["@mozilla.org/widget/idleservice;1"].getService(Ci.nsIIdleService);
+
+add_task(function* testWithRealIdleService() {
+ function background() {
+ browser.test.onMessage.addListener((msg, ...args) => {
+ let detectionInterval = args[0];
+ if (msg == "addListener") {
+ browser.idle.queryState(detectionInterval).then(status => {
+ browser.test.assertEq("active", status, "Idle status is active");
+ });
+ browser.idle.setDetectionInterval(detectionInterval);
+ browser.idle.onStateChanged.addListener(newState => {
+ browser.test.assertEq("idle", newState, "listener fired with the expected state");
+ browser.test.sendMessage("listenerFired");
+ });
+ } else if (msg == "checkState") {
+ browser.idle.queryState(detectionInterval).then(status => {
+ browser.test.assertEq("idle", status, "Idle status is idle");
+ browser.test.notifyPass("idle");
+ });
+ }
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ yield extension.startup();
+ let idleTime = idleService.idleTime;
+ let detectionInterval = Math.max(Math.ceil(idleTime / 1000) + 2, 15);
+ info(`idleTime: ${idleTime}, detectionInterval: ${detectionInterval}`);
+ extension.sendMessage("addListener", detectionInterval);
+ info("Listener added");
+ yield extension.awaitMessage("listenerFired");
+ info("Listener fired");
+ extension.sendMessage("checkState", detectionInterval);
+ yield extension.awaitFinish("idle");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html
new file mode 100644
index 000000000..e3098e6b1
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html
@@ -0,0 +1,50 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://testing-common/TestUtils.jsm");
+
+const {GlobalManager} = Cu.import("resource://gre/modules/Extension.jsm");
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* testShutdownCleanup() {
+ is(GlobalManager.initialized, false,
+ "GlobalManager start as not initialized");
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: function() {
+ browser.test.notifyPass("background page loaded");
+ },
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("background page loaded");
+
+ is(GlobalManager.initialized, true,
+ "GlobalManager has been initialized once an extension is started");
+
+ yield extension.unload();
+
+ is(GlobalManager.initialized, false,
+ "GlobalManager has been uninitialized once all the webextensions have been stopped");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html
new file mode 100644
index 000000000..010769500
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html
@@ -0,0 +1,164 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+// Test that storage used by a webextension (through localStorage,
+// indexedDB, and browser.storage.local) gets cleaned up when the
+// extension is uninstalled.
+add_task(function* test_uninstall() {
+ function writeData() {
+ localStorage.setItem("hello", "world");
+
+ let idbPromise = new Promise((resolve, reject) => {
+ let req = indexedDB.open("test");
+ req.onerror = e => {
+ reject(new Error(`indexedDB open failed with ${e.errorCode}`));
+ };
+
+ req.onupgradeneeded = e => {
+ let db = e.target.result;
+ db.createObjectStore("store", {keyPath: "name"});
+ };
+
+ req.onsuccess = e => {
+ let db = e.target.result;
+ let transaction = db.transaction("store", "readwrite");
+ let addreq = transaction.objectStore("store")
+ .add({name: "hello", value: "world"});
+ addreq.onerror = addreqError => {
+ reject(new Error(`add to indexedDB failed with ${addreqError.errorCode}`));
+ };
+ addreq.onsuccess = () => {
+ resolve();
+ };
+ };
+ });
+
+ let browserStoragePromise = browser.storage.local.set({hello: "world"});
+
+ Promise.all([idbPromise, browserStoragePromise]).then(() => {
+ browser.test.sendMessage("finished");
+ });
+ }
+
+ function readData() {
+ let matchLocalStorage = (localStorage.getItem("hello") == "world");
+
+ let idbPromise = new Promise((resolve, reject) => {
+ let req = indexedDB.open("test");
+ req.onerror = e => {
+ reject(new Error(`indexedDB open failed with ${e.errorCode}`));
+ };
+
+ req.onupgradeneeded = e => {
+ // no database, data is not present
+ resolve(false);
+ };
+
+ req.onsuccess = e => {
+ let db = e.target.result;
+ let transaction = db.transaction("store", "readwrite");
+ let addreq = transaction.objectStore("store").get("hello");
+ addreq.onerror = addreqError => {
+ reject(new Error(`read from indexedDB failed with ${addreqError.errorCode}`));
+ };
+ addreq.onsuccess = () => {
+ let match = (addreq.result.value == "world");
+ resolve(match);
+ };
+ };
+ });
+
+ let browserStoragePromise = browser.storage.local.get("hello").then(result => {
+ return (Object.keys(result).length == 1 && result.hello == "world");
+ });
+
+ Promise.all([idbPromise, browserStoragePromise])
+ .then(([matchIDB, matchBrowserStorage]) => {
+ let result = {matchLocalStorage, matchIDB, matchBrowserStorage};
+ browser.test.sendMessage("results", result);
+ });
+ }
+
+ const ID = "storage.cleanup@tests.mozilla.org";
+
+ // Use a test-only pref to leave the addonid->uuid mapping around after
+ // uninstall so that we can re-attach to the same storage. Also set
+ // the pref to prevent cleaning up storage on uninstall so we can test
+ // that the "keep uuid" logic works correctly. Do the storage flag in
+ // a separate prefEnv so we can pop it below, leaving the uuid flag set.
+ yield SpecialPowers.pushPrefEnv({
+ set: [["extensions.webextensions.keepUuidOnUninstall", true]],
+ });
+ yield SpecialPowers.pushPrefEnv({
+ set: [["extensions.webextensions.keepStorageOnUninstall", true]],
+ });
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: writeData,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["storage"],
+ },
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("finished");
+ yield extension.unload();
+
+ // Check that we can still see data we wrote to storage but clear the
+ // "leave storage" flag so our storaged gets cleared on uninstall.
+ // This effectively tests the keepUuidOnUninstall logic, which ensures
+ // that when we read storage again and check that it is cleared, that
+ // it is actually a meaningful test!
+ yield SpecialPowers.popPrefEnv();
+ extension = ExtensionTestUtils.loadExtension({
+ background: readData,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["storage"],
+ },
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ let results = yield extension.awaitMessage("results");
+ is(results.matchLocalStorage, true, "localStorage data is still present");
+ is(results.matchIDB, true, "indexedDB data is still present");
+ is(results.matchBrowserStorage, true, "browser.storage.local data is still present");
+
+ yield extension.unload();
+
+ // Read again. This time, our data should be gone.
+ extension = ExtensionTestUtils.loadExtension({
+ background: readData,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["storage"],
+ },
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ results = yield extension.awaitMessage("results");
+ is(results.matchLocalStorage, false, "localStorage data was cleared");
+ is(results.matchIDB, false, "indexedDB data was cleared");
+ is(results.matchBrowserStorage, false, "browser.storage.local data was cleared");
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html
new file mode 100644
index 000000000..573c08806
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html
@@ -0,0 +1,53 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/**
+ * This test is asserting that moz-extension: URLs are recognized as trustworthy local origins
+ */
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(this, "gContentSecurityManager",
+ "@mozilla.org/contentsecuritymanager;1",
+ "nsIContentSecurityManager");
+
+add_task(function* () {
+ function background() {
+ browser.test.sendMessage("ready", browser.runtime.getURL("/test.html"));
+ }
+
+ let extensionData = {
+ background,
+ files: {
+ "test.html": `<html><head></head><body></body></html>`,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let url = yield extension.awaitMessage("ready");
+
+ let uri = NetUtil.newURI(url);
+ let principal = Services.scriptSecurityManager.getCodebasePrincipal(uri);
+ is(gContentSecurityManager.isOriginPotentiallyTrustworthy(principal), true);
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html
new file mode 100644
index 000000000..768eb31fd
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html
@@ -0,0 +1,83 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* webnav_unresolved_uri_on_expected_URI_scheme() {
+ function background() {
+ let checkURLs;
+
+ browser.webNavigation.onCompleted.addListener(async msg => {
+ if (checkURLs.length > 0) {
+ let expectedURL = checkURLs.shift();
+ browser.test.assertEq(expectedURL, msg.url, "Got the expected URL");
+ await browser.tabs.remove(msg.tabId);
+ browser.test.sendMessage("next");
+ }
+ });
+
+ browser.test.onMessage.addListener((name, urls) => {
+ if (name == "checkURLs") {
+ checkURLs = urls;
+ }
+ });
+
+ browser.test.sendMessage("ready", browser.runtime.getURL("/tab.html"));
+ }
+
+ let extensionData = {
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background,
+ files: {
+ "tab.html": `<!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ </html>
+ `,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ let checkURLs = [
+ "resource://gre/modules/Services.jsm",
+ "chrome://mochikit/content/tests/SimpleTest/SimpleTest.js",
+ "about:mozilla",
+ ];
+
+ let tabURL = yield extension.awaitMessage("ready");
+ checkURLs.push(tabURL);
+
+ extension.sendMessage("checkURLs", checkURLs);
+
+ for (let url of checkURLs) {
+ window.open(url);
+ yield extension.awaitMessage("next");
+ }
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html
new file mode 100644
index 000000000..a13c4d475
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html
@@ -0,0 +1,96 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+Cu.import(SimpleTest.getTestFileURL("webrequest_test.jsm"));
+let {testFetch, testXHR} = webrequest_test;
+
+// Here we test that any requests originating from a system principal are not
+// accessible through WebRequest. text_ext_webrequest_background_events tests
+// non-system principal requests.
+
+let testExtension = {
+ manifest: {
+ permissions: [
+ "webRequest",
+ "<all_urls>",
+ ],
+ },
+ background() {
+ let eventNames = [
+ "onBeforeRequest",
+ "onBeforeSendHeaders",
+ "onSendHeaders",
+ "onHeadersReceived",
+ "onResponseStarted",
+ "onCompleted",
+ ];
+
+ function listener(name, details) {
+ // If we get anything, we failed. Removing the system principal check
+ // in ext-webrequest triggers this failure.
+ browser.test.fail(`recieved ${name}`);
+ }
+
+ for (let name of eventNames) {
+ browser.webRequest[name].addListener(
+ listener.bind(null, name),
+ {urls: ["https://example.com/*"]}
+ );
+ }
+ },
+};
+
+add_task(function* test_webRequest_chromeworker_events() {
+ let extension = ExtensionTestUtils.loadExtension(testExtension);
+ yield extension.startup();
+ yield new Promise(resolve => {
+ let worker = new ChromeWorker("webrequest_chromeworker.js");
+ worker.onmessage = event => {
+ ok("chrome worker fetch finished");
+ resolve();
+ };
+ worker.postMessage("go");
+ });
+ yield extension.unload();
+});
+
+add_task(function* test_webRequest_chromepage_events() {
+ let extension = ExtensionTestUtils.loadExtension(testExtension);
+ yield extension.startup();
+ yield new Promise(resolve => {
+ fetch("https://example.com/example.txt").then(() => {
+ ok("test page loaded");
+ resolve();
+ });
+ });
+ yield extension.unload();
+});
+
+add_task(function* test_webRequest_jsm_events() {
+ let extension = ExtensionTestUtils.loadExtension(testExtension);
+ yield extension.startup();
+ yield testFetch("https://example.com/example.txt").then(() => {
+ ok("fetch page loaded");
+ });
+ yield testXHR("https://example.com/example.txt").then(() => {
+ ok("xhr page loaded");
+ });
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html b/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html
new file mode 100644
index 000000000..29a148063
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html
@@ -0,0 +1,61 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" href="chrome://mochikit/contents/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* global OS */
+
+Cu.import("resource://gre/modules/osfile.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
+
+// Test that the default paths searched for native host manifests
+// are the ones we expect.
+add_task(function* test_default_paths() {
+ let expectUser, expectGlobal;
+ switch (AppConstants.platform) {
+ case "macosx": {
+ expectUser = OS.Path.join(OS.Constants.Path.homeDir,
+ "Library/Application Support/Mozilla/NativeMessagingHosts");
+ expectGlobal = "/Library/Application Support/Mozilla/NativeMessagingHosts";
+
+ break;
+ }
+
+ case "linux": {
+ expectUser = OS.Path.join(OS.Constants.Path.homeDir, ".mozilla/native-messaging-hosts");
+
+ const libdir = AppConstants.HAVE_USR_LIB64_DIR ? "lib64" : "lib";
+ expectGlobal = OS.Path.join("/usr", libdir, "mozilla/native-messaging-hosts");
+ break;
+ }
+
+ default:
+ // Fixed filesystem paths are only defined for MacOS and Linux,
+ // there's nothing to test on other platforms.
+ ok(false, `This test does not apply on ${AppConstants.platform}`);
+ break;
+ }
+
+ let userDir = Services.dirsvc.get("XREUserNativeMessaging", Ci.nsIFile).path;
+ is(userDir, expectUser, "user-specific native messaging directory is correct");
+
+ let globalDir = Services.dirsvc.get("XRESysNativeMessaging", Ci.nsIFile).path;
+ is(globalDir, expectGlobal, "system-wide native messaing directory is correct");
+});
+
+</script>
+
+</body>
+</html>
+
diff --git a/toolkit/components/webextensions/test/mochitest/test_clipboard.html b/toolkit/components/webextensions/test/mochitest/test_clipboard.html
new file mode 100644
index 000000000..900ee5f10
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_clipboard.html
@@ -0,0 +1,140 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>clipboard permission test</title>
+ <script src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script src="head.js"></script>
+ <link rel="stylesheet" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+function doCopy(txt) {
+ let field = document.createElement("textarea");
+ document.body.appendChild(field);
+ field.value = txt;
+ field.select();
+ return document.execCommand("copy");
+}
+
+add_task(function* no_permission_deny_copy() {
+ function backgroundScript() {
+ browser.test.assertEq(false, doCopy("whatever"),
+ "copy should be denied without permission");
+ browser.test.sendMessage("ready");
+ }
+ let extensionData = {
+ background: `${doCopy};(${backgroundScript})();`,
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitMessage("ready");
+
+ yield extension.unload();
+});
+
+/** Selecting text in a bg page is not possible, skip test until it's fixed.
+add_task(function* with_permission_allow_copy() {
+ function backgroundScript() {
+ browser.test.onMessage.addListener(txt => {
+ browser.test.assertEq(true, doCopy(txt),
+ "copy should be allowed with permission");
+ });
+ browser.test.sendMessage("ready");
+ }
+ let extensionData = {
+ background: `${doCopy};(${backgroundScript})();`,
+ manifest: {
+ permissions: [
+ "clipboardWrite",
+ ],
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ const DUMMY_STR = "dummy string to copy";
+ yield new Promise(resolve => {
+ SimpleTest.waitForClipboard(DUMMY_STR, () => {
+ extension.sendMessage(DUMMY_STR);
+ }, resolve, resolve);
+ });
+
+ yield extension.unload();
+}); */
+
+add_task(function* content_script_no_permission_deny_copy() {
+ function contentScript() {
+ browser.test.assertEq(false, doCopy("whatever"),
+ "copy should be denied without permission");
+ browser.test.sendMessage("ready");
+ }
+ let extensionData = {
+ manifest: {
+ content_scripts: [{
+ js: ["contentscript.js"],
+ matches: ["http://mochi.test/*/file_sample.html"],
+ }],
+ },
+ files: {
+ "contentscript.js": `${doCopy};(${contentScript})();`,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitMessage("ready");
+ win.close();
+
+ yield extension.unload();
+});
+
+add_task(function* content_script_with_permission_allow_copy() {
+ function contentScript() {
+ browser.test.onMessage.addListener(txt => {
+ browser.test.assertEq(true, doCopy(txt),
+ "copy should be allowed with permission");
+ });
+ browser.test.sendMessage("ready");
+ }
+ let extensionData = {
+ manifest: {
+ content_scripts: [{
+ js: ["contentscript.js"],
+ matches: ["http://mochi.test/*/file_sample.html"],
+ }],
+ permissions: [
+ "clipboardWrite",
+ ],
+ },
+ files: {
+ "contentscript.js": `${doCopy};(${contentScript})();`,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitMessage("ready");
+
+ const DUMMY_STR = "dummy string to copy in content script";
+ yield new Promise(resolve => {
+ SimpleTest.waitForClipboard(DUMMY_STR, () => {
+ extension.sendMessage(DUMMY_STR);
+ }, resolve, resolve);
+ });
+
+ win.close();
+
+ yield extension.unload();
+});
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js b/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js
new file mode 100644
index 000000000..0f617c37e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js
@@ -0,0 +1,158 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+// Tests whether not too many APIs are visible by default.
+// This file is used by test_ext_all_apis.html in browser/ and mobile/android/,
+// which may modify the following variables to add or remove expected APIs.
+/* globals expectedContentApisTargetSpecific */
+/* globals expectedBackgroundApisTargetSpecific */
+
+// Generates a list of expectations.
+function generateExpectations(list) {
+ return list.reduce((allApis, path) => {
+ return allApis.concat(`browser.${path}`, `chrome.${path}`);
+ }, []).sort();
+}
+
+let expectedCommonApis = [
+ "extension.getURL",
+ "extension.inIncognitoContext",
+ "extension.lastError",
+ "i18n.detectLanguage",
+ "i18n.getAcceptLanguages",
+ "i18n.getMessage",
+ "i18n.getUILanguage",
+ "runtime.OnInstalledReason",
+ "runtime.OnRestartRequiredReason",
+ "runtime.PlatformArch",
+ "runtime.PlatformOs",
+ "runtime.RequestUpdateCheckStatus",
+ "runtime.getManifest",
+ "runtime.connect",
+ "runtime.getURL",
+ "runtime.id",
+ "runtime.lastError",
+ "runtime.onConnect",
+ "runtime.onMessage",
+ "runtime.sendMessage",
+ // If you want to add a new powerful test API, please see bug 1287233.
+ "test.assertEq",
+ "test.assertFalse",
+ "test.assertRejects",
+ "test.assertThrows",
+ "test.assertTrue",
+ "test.fail",
+ "test.log",
+ "test.notifyFail",
+ "test.notifyPass",
+ "test.onMessage",
+ "test.sendMessage",
+ "test.succeed",
+];
+
+let expectedContentApis = [
+ ...expectedCommonApis,
+ ...expectedContentApisTargetSpecific,
+];
+
+let expectedBackgroundApis = [
+ ...expectedCommonApis,
+ ...expectedBackgroundApisTargetSpecific,
+ "extension.ViewType",
+ "extension.getBackgroundPage",
+ "extension.getViews",
+ "extension.isAllowedFileSchemeAccess",
+ "extension.isAllowedIncognitoAccess",
+ // Note: extensionTypes is not visible in Chrome.
+ "extensionTypes.ImageFormat",
+ "extensionTypes.RunAt",
+ "management.ExtensionDisabledReason",
+ "management.ExtensionInstallType",
+ "management.ExtensionType",
+ "management.getSelf",
+ "management.uninstallSelf",
+ "runtime.getBackgroundPage",
+ "runtime.getBrowserInfo",
+ "runtime.getPlatformInfo",
+ "runtime.onInstalled",
+ "runtime.onStartup",
+ "runtime.onUpdateAvailable",
+ "runtime.openOptionsPage",
+ "runtime.reload",
+ "runtime.setUninstallURL",
+];
+
+function sendAllApis() {
+ function isEvent(key, val) {
+ if (!/^on[A-Z]/.test(key)) {
+ return false;
+ }
+ let eventKeys = [];
+ for (let prop in val) {
+ eventKeys.push(prop);
+ }
+ eventKeys = eventKeys.sort().join();
+ return eventKeys === "addListener,hasListener,removeListener";
+ }
+ function mayRecurse(key, val) {
+ if (Object.keys(val).filter(k => !/^[A-Z\-0-9_]+$/.test(k)).length === 0) {
+ // Don't recurse on constants and empty objects.
+ return false;
+ }
+ return !isEvent(key, val);
+ }
+
+ let results = [];
+ function diveDeeper(path, obj) {
+ for (let key in obj) {
+ let val = obj[key];
+ if (typeof val == "object" && val !== null && mayRecurse(key, val)) {
+ diveDeeper(`${path}.${key}`, val);
+ } else if (val !== undefined) {
+ results.push(`${path}.${key}`);
+ }
+ }
+ }
+ diveDeeper("browser", browser);
+ diveDeeper("chrome", chrome);
+ browser.test.sendMessage("allApis", results.sort());
+}
+
+add_task(function* test_enumerate_content_script_apis() {
+ let extensionData = {
+ manifest: {
+ content_scripts: [{
+ matches: ["http://mochi.test/*/file_sample.html"],
+ js: ["contentscript.js"],
+ run_at: "document_start",
+ }],
+ },
+ files: {
+ "contentscript.js": sendAllApis,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ let actualApis = yield extension.awaitMessage("allApis");
+ win.close();
+ let expectedApis = generateExpectations(expectedContentApis);
+ isDeeply(actualApis, expectedApis, "content script APIs");
+
+ yield extension.unload();
+});
+
+add_task(function* test_enumerate_background_script_apis() {
+ let extensionData = {
+ background: sendAllApis,
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ let actualApis = yield extension.awaitMessage("allApis");
+ let expectedApis = generateExpectations(expectedBackgroundApis);
+ isDeeply(actualApis, expectedApis, "background script APIs");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html
new file mode 100644
index 000000000..f43a59f81
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for privilege escalation into content pages</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* testBackgroundWindow() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background: function() {
+ const BASE = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest";
+
+ browser.test.log("background script executed");
+ window.location = `${BASE}/file_privilege_escalation.html`;
+ },
+ });
+
+ let awaitConsole = new Promise(resolve => {
+ let chromeScript = SpecialPowers.loadChromeScript(
+ SimpleTest.getTestFileURL("file_ext_test_api_injection.js"));
+
+ chromeScript.addMessageListener("console-message", resolve);
+ });
+
+ yield extension.startup();
+
+ let message = yield awaitConsole;
+
+ ok(message.message.includes("WebExt Privilege Escalation: typeof(browser) = undefined"),
+ "Document does not have `browser` APIs.");
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html
new file mode 100644
index 000000000..bff7190cb
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html
@@ -0,0 +1,47 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for background page canvas rendering</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_background_canvas() {
+ function background() {
+ try {
+ let canvas = document.createElement("canvas");
+
+ let context = canvas.getContext("2d");
+
+ // This ensures that we have a working PresShell, and can successfully
+ // calculate font metrics.
+ context.font = "8pt fixed";
+
+ browser.test.notifyPass("background-canvas");
+ } catch (e) {
+ browser.test.fail(`Error: ${e} :: ${e.stack}`);
+ browser.test.notifyFail("background-canvas");
+ }
+ }
+
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+ yield extension.awaitFinish("background-canvas");
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html
new file mode 100644
index 000000000..f4fcf3d34
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html
@@ -0,0 +1,47 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test _generated_background_page.html</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+add_task(function* test_url_of_generated_background_page() {
+ function backgroundScript() {
+ const EXPECTED_URL = browser.runtime.getURL("/_generated_background_page.html");
+ browser.test.assertEq(EXPECTED_URL, location.href);
+ browser.test.sendMessage("script done", EXPECTED_URL);
+ }
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ background: {
+ scripts: ["bg.js"],
+ },
+ web_accessible_resources: ["_generated_background_page.html"],
+ },
+ files: {
+ "bg.js": backgroundScript,
+ },
+ });
+
+ yield extension.startup();
+ const EXPECTED_URL = yield extension.awaitMessage("script done");
+
+ let win = window.open(EXPECTED_URL);
+ ok(win, "Should open new tab at URL: " + EXPECTED_URL);
+ yield extension.awaitMessage("script done");
+ win.close();
+
+ yield extension.unload();
+});
+
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html
new file mode 100644
index 000000000..bb6b2e970
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html
@@ -0,0 +1,76 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for background script teardown</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+add_task(function* test_background_reload_and_unload() {
+ function background() {
+ browser.test.onMessage.addListener(msg => {
+ browser.test.assertEq("reload-background", msg);
+ location.reload();
+ });
+ browser.test.sendMessage("background-url", location.href);
+ }
+
+ let chromeScript = SpecialPowers.loadChromeScript(
+ SimpleTest.getTestFileURL("file_teardown_test.js"));
+ yield chromeScript.promiseOneMessage("chromescript-startup");
+
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ function* getContextEvents() {
+ chromeScript.sendAsyncMessage("get-context-events");
+ let contextEvents = yield chromeScript.promiseOneMessage("context-events");
+ return contextEvents.filter(event => event.extensionId == extension.id);
+ }
+ yield extension.startup();
+ let backgroundUrl = yield extension.awaitMessage("background-url");
+
+ let contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1,
+ "ExtensionContext state change after loading an extension");
+ is(contextEvents[0].eventType, "load");
+ is(contextEvents[0].url, backgroundUrl,
+ "The ExtensionContext should be the background page");
+
+ extension.sendMessage("reload-background");
+ yield extension.awaitMessage("background-url");
+
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 2,
+ "ExtensionContext state changes after reloading the background page");
+ is(contextEvents[0].eventType, "unload",
+ "Unload ExtensionContext of background page");
+ is(contextEvents[0].url, backgroundUrl, "ExtensionContext URL = background");
+ is(contextEvents[1].eventType, "load",
+ "Create new ExtensionContext for background page");
+ is(contextEvents[1].url, backgroundUrl, "ExtensionContext URL = background");
+ yield extension.unload();
+
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1,
+ "ExtensionContext state change after unloading the extension");
+ is(contextEvents[0].eventType, "unload",
+ "Unload ExtensionContext for background page after extension unloads");
+ is(contextEvents[0].url, backgroundUrl, "ExtensionContext URL = background");
+
+ chromeScript.sendAsyncMessage("cleanup");
+ chromeScript.destroy();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html b/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html
new file mode 100644
index 000000000..a36f29563
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html
@@ -0,0 +1,162 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension CSP test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/**
+ * Tests that content security policies for an add-on are actually applied to *
+ * documents that belong to it. This tests both the base policies and add-on
+ * specific policies, and ensures that the parsed policies applied to the
+ * document's principal match what was specified in the policy string.
+ *
+ * @param {object} [customCSP]
+ */
+function* testPolicy(customCSP = null) {
+ let baseURL;
+
+ let baseCSP = {
+ "object-src": ["blob:", "filesystem:", "https://*", "moz-extension:", "'self'"],
+ "script-src": ["'unsafe-eval'", "'unsafe-inline'", "blob:", "filesystem:", "https://*", "moz-extension:", "'self'"],
+ };
+
+ let addonCSP = {
+ "object-src": ["'self'"],
+ "script-src": ["'self'"],
+ };
+
+ let content_security_policy = null;
+
+ if (customCSP) {
+ for (let key of Object.keys(customCSP)) {
+ addonCSP[key] = customCSP[key].split(/\s+/);
+ }
+
+ content_security_policy = Object.keys(customCSP)
+ .map(key => `${key} ${customCSP[key]}`)
+ .join("; ");
+ }
+
+
+ function filterSelf(sources) {
+ return sources.map(src => src == "'self'" ? baseURL : src);
+ }
+
+ function checkSource(name, policy, expected) {
+ is(JSON.stringify(policy[name].sort()),
+ JSON.stringify(filterSelf(expected[name]).sort()),
+ `Expected value for ${name}`);
+ }
+
+ function checkCSP(csp, location) {
+ let policies = csp["csp-policies"];
+
+ info(`Base policy for ${location}`);
+
+ is(policies[0]["report-only"], false, "Policy is not report-only");
+ checkSource("object-src", policies[0], baseCSP);
+ checkSource("script-src", policies[0], baseCSP);
+
+ info(`Add-on policy for ${location}`);
+
+ is(policies[1]["report-only"], false, "Policy is not report-only");
+ checkSource("object-src", policies[1], addonCSP);
+ checkSource("script-src", policies[1], addonCSP);
+ }
+
+
+ function getCSP(window) {
+ let {cspJSON} = SpecialPowers.Cu.getObjectPrincipal(window);
+ return JSON.parse(cspJSON);
+ }
+
+ function background(getCSPFn) {
+ browser.test.sendMessage("base-url", browser.extension.getURL("").replace(/\/$/, ""));
+
+ browser.test.sendMessage("background-csp", getCSPFn(window));
+ }
+
+ function tabScript(getCSPFn) {
+ browser.test.sendMessage("tab-csp", getCSPFn(window));
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${background})(${getCSP})`,
+
+ files: {
+ "tab.html": `<html><head><meta charset="utf-8">
+ <script src="tab.js"></${"script"}></head></html>`,
+
+ "tab.js": `(${tabScript})(${getCSP})`,
+
+ "content.html": `<html><head><meta charset="utf-8"></head></html>`,
+ },
+
+ manifest: {
+ content_security_policy,
+
+ web_accessible_resources: ["content.html", "tab.html"],
+ },
+ });
+
+
+ info(`Testing CSP for policy: ${content_security_policy}`);
+
+ yield extension.startup();
+
+ baseURL = yield extension.awaitMessage("base-url");
+
+
+ let win1 = window.open(`${baseURL}/tab.html`);
+
+ let frame = document.createElement("iframe");
+ frame.src = `${baseURL}/content.html`;
+ document.body.appendChild(frame);
+
+ yield new Promise(resolve => {
+ frame.onload = resolve;
+ });
+
+
+ let backgroundCSP = yield extension.awaitMessage("background-csp");
+ checkCSP(backgroundCSP, "background page");
+
+ let tabCSP = yield extension.awaitMessage("tab-csp");
+ checkCSP(tabCSP, "tab page");
+
+ let contentCSP = getCSP(frame.contentWindow);
+ checkCSP(contentCSP, "content frame");
+
+
+ win1.close();
+ frame.remove();
+
+ yield extension.unload();
+}
+
+add_task(function* testCSP() {
+ yield testPolicy(null);
+
+ let hash = "'sha256-NjZhMDQ1YjQ1MjEwMmM1OWQ4NDBlYzA5N2Q1OWQ5NDY3ZTEzYTNmMzRmNjQ5NGU1MzlmZmQzMmMxYmIzNWYxOCAgLQo='";
+
+ yield testPolicy({
+ "object-src": "'self' https://*.example.com",
+ "script-src": `'self' https://*.example.com 'unsafe-eval' ${hash}`,
+ });
+
+ yield testPolicy({
+ "object-src": "'none'",
+ "script-src": `'self'`,
+ });
+});
+</script>
+</body>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html
new file mode 100644
index 000000000..39f1bfabd
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html
@@ -0,0 +1,116 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript() {
+ function background() {
+ browser.runtime.onMessage.addListener(([msg, expectedStates, readyState], sender) => {
+ if (msg == "chrome-namespace-ok") {
+ browser.test.sendMessage(msg);
+ return;
+ }
+
+ browser.test.assertEq("script-run", msg, "message type is correct");
+ browser.test.assertTrue(expectedStates.includes(readyState),
+ `readyState "${readyState}" is one of [${expectedStates}]`);
+ browser.test.sendMessage("script-run-" + expectedStates[0]);
+ });
+ }
+
+ function contentScriptStart() {
+ browser.runtime.sendMessage(["script-run", ["loading"], document.readyState]);
+ }
+ function contentScriptEnd() {
+ browser.runtime.sendMessage(["script-run", ["interactive", "complete"], document.readyState]);
+ }
+ function contentScriptIdle() {
+ browser.runtime.sendMessage(["script-run", ["complete"], document.readyState]);
+ }
+
+ function contentScript() {
+ let manifest = browser.runtime.getManifest();
+ void manifest.applications.gecko.id;
+ chrome.runtime.sendMessage(["chrome-namespace-ok"]);
+ }
+
+ let extensionData = {
+ manifest: {
+ applications: {gecko: {id: "contentscript@tests.mozilla.org"}},
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script_start.js"],
+ "run_at": "document_start",
+ },
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script_end.js"],
+ "run_at": "document_end",
+ },
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script_idle.js"],
+ "run_at": "document_idle",
+ },
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ },
+ ],
+ },
+ background,
+
+ files: {
+ "content_script_start.js": contentScriptStart,
+ "content_script_end.js": contentScriptEnd,
+ "content_script_idle.js": contentScriptIdle,
+ "content_script.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ let loadingCount = 0;
+ let interactiveCount = 0;
+ let completeCount = 0;
+ extension.onMessage("script-run-loading", () => { loadingCount++; });
+ extension.onMessage("script-run-interactive", () => { interactiveCount++; });
+
+ let completePromise = new Promise(resolve => {
+ extension.onMessage("script-run-complete", () => { completeCount++; resolve(); });
+ });
+
+ let chromeNamespacePromise = extension.awaitMessage("chrome-namespace-ok");
+
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), completePromise, chromeNamespacePromise]);
+ info("test page loaded");
+
+ win.close();
+
+ is(loadingCount, 1, "document_start script ran exactly once");
+ is(interactiveCount, 1, "document_end script ran exactly once");
+ is(completeCount, 1, "document_idle script ran exactly once");
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html
new file mode 100644
index 000000000..3766678e7
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html
@@ -0,0 +1,117 @@
+<!doctype html>
+<html>
+<head>
+ <title>Test content script match_about_blank option</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript_about_blank() {
+ const manifest = {
+ content_scripts: [
+ {
+ match_about_blank: true,
+ matches: ["http://mochi.test/*/file_with_about_blank.html", "http://example.com/*"],
+ all_frames: true,
+ css: ["all.css"],
+ js: ["all.js"],
+ }, {
+ matches: ["http://mochi.test/*/file_with_about_blank.html"],
+ css: ["mochi_without.css"],
+ js: ["mochi_without.js"],
+ all_frames: true,
+ }, {
+ match_about_blank: true,
+ matches: ["http://mochi.test/*/file_with_about_blank.html"],
+ css: ["mochi_with.css"],
+ js: ["mochi_with.js"],
+ all_frames: true,
+ },
+ ],
+ };
+
+ const files = {
+ "all.js": function() {
+ browser.runtime.sendMessage("all");
+ },
+ "all.css": `
+ body { color: red; }
+ `,
+ "mochi_without.js": function() {
+ browser.runtime.sendMessage("mochi_without");
+ },
+ "mochi_without.css": `
+ body { background: yellow; }
+ `,
+ "mochi_with.js": function() {
+ browser.runtime.sendMessage("mochi_with");
+ },
+ "mochi_with.css": `
+ body { text-align: right; }
+ `,
+ };
+
+ function background() {
+ browser.runtime.onMessage.addListener((script, {url}) => {
+ const kind = url.startsWith("about:") ? url : "top";
+ browser.test.sendMessage("script", [script, kind, url]);
+ browser.test.sendMessage(`${script}:${kind}`);
+ });
+ }
+
+ const PATH = "tests/toolkit/components/extensions/test/mochitest/file_with_about_blank.html";
+ const extension = ExtensionTestUtils.loadExtension({manifest, files, background});
+ yield extension.startup();
+
+ let count = 0;
+ extension.onMessage("script", script => {
+ info(`script ran: ${script}`);
+ count++;
+ });
+
+ let win = window.open("http://example.com/" + PATH);
+ yield Promise.all([
+ extension.awaitMessage("all:top"),
+ extension.awaitMessage("all:about:blank"),
+ extension.awaitMessage("all:about:srcdoc"),
+ ]);
+ is(count, 3, "exactly 3 scripts ran");
+ win.close();
+
+ win = window.open("http://mochi.test:8888/" + PATH);
+ yield Promise.all([
+ extension.awaitMessage("all:top"),
+ extension.awaitMessage("all:about:blank"),
+ extension.awaitMessage("all:about:srcdoc"),
+ extension.awaitMessage("mochi_without:top"),
+ extension.awaitMessage("mochi_with:top"),
+ extension.awaitMessage("mochi_with:about:blank"),
+ extension.awaitMessage("mochi_with:about:srcdoc"),
+ ]);
+
+ let style = win.getComputedStyle(win.document.body);
+ is(style.color, "rgb(255, 0, 0)", "top window text color is red");
+ is(style.backgroundColor, "rgb(255, 255, 0)", "top window background is yellow");
+ is(style.textAlign, "right", "top window text is right-aligned");
+
+ let a_b = win.document.getElementById("a_b");
+ style = a_b.contentWindow.getComputedStyle(a_b.contentDocument.body);
+ is(style.color, "rgb(255, 0, 0)", "about:blank iframe text color is red");
+ is(style.backgroundColor, "transparent", "about:blank iframe background is transparent");
+ is(style.textAlign, "right", "about:blank text is right-aligned");
+
+ is(count, 10, "exactly 7 more scripts ran");
+ win.close();
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html
new file mode 100644
index 000000000..abf3d349f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html
@@ -0,0 +1,88 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for privilege escalation into iframe with content script APIs</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<!-- WORKAROUND: this textarea hack is used to contain the html page source without escaping it -->
+<textarea id="test-asset">
+ <!DOCTYPE HTML>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <script type="text/javascript" src="./content_script_iframe.js">
+ </script>
+ </head>
+ </html>
+</textarea>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript_api_injection() {
+ function contentScript() {
+ let iframe = document.createElement("iframe");
+ iframe.setAttribute("src", browser.runtime.getURL("content_script_iframe.html"));
+ document.body.appendChild(iframe);
+ }
+
+ function contentScriptIframe() {
+ const BASE = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest";
+ window.location = `${BASE}/file_privilege_escalation.html`;
+ }
+
+ let extensionData = {
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ },
+ ],
+ "web_accessible_resources": [
+ "content_script_iframe.html",
+ ],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ "content_script_iframe.js": contentScriptIframe,
+ "content_script_iframe.html": document.querySelector("#test-asset").textContent,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ let awaitConsole = new Promise(resolve => {
+ let chromeScript = SpecialPowers.loadChromeScript(
+ SimpleTest.getTestFileURL("file_ext_test_api_injection.js"));
+
+ chromeScript.addMessageListener("console-message", resolve);
+ });
+
+ yield extension.startup();
+ info("extension loaded");
+
+ let win = window.open("file_sample.html");
+
+ let message = yield awaitConsole;
+
+ ok(message.message.includes("WebExt Privilege Escalation: typeof(browser) = undefined"),
+ "Document does not have `browser` APIs.");
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html
new file mode 100644
index 000000000..d78f7ce02
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html>
+<head>
+ <title>Test content script async loading</title>
+ <script src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<script>
+"use strict";
+
+add_task(function* test_async_loading() {
+ const adder = `(function add(a = 1) { this.count += a; })();\n`;
+ const extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ content_scripts: [{
+ matches: ["https://example.org/"],
+ js: ["first.js", "second.js"],
+ }],
+ },
+ files: {
+ "first.js": `
+ this.count = 0;
+ ${adder.repeat(50000)}; // 2Mb
+ browser.test.assertEq(this.count, 50000, "A 50k line script");
+
+ this.order = (this.order || 0) + 1;
+ browser.test.sendMessage("first", this.order);
+ `,
+ "second.js": `
+ this.order = (this.order || 0) + 1;
+ browser.test.sendMessage("second", this.order);
+ `,
+ },
+ });
+
+ yield extension.startup();
+ const win = window.open("https://example.org/");
+
+ const [first, second] = yield Promise.all([
+ extension.awaitMessage("first"),
+ extension.awaitMessage("second"),
+ ]);
+
+ is(first, 1, "first.js finished execution first.");
+ is(second, 2, "second.js finished execution second.");
+
+ yield extension.unload();
+ win.close();
+});
+
+</script>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html
new file mode 100644
index 000000000..97b1645dd
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html
@@ -0,0 +1,81 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script contexts</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* test_contentscript_context() {
+ function contentScript() {
+ browser.test.sendMessage("content-script-ready");
+
+ window.addEventListener("pagehide", () => {
+ browser.test.sendMessage("content-script-hide");
+ }, true);
+ window.addEventListener("pageshow", () => {
+ browser.test.sendMessage("content-script-show");
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ content_scripts: [{
+ "matches": ["http://example.com/"],
+ "js": ["content_script.js"],
+ "run_at": "document_start",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+ });
+
+ yield extension.startup();
+
+ let win = window.open("http://example.com/");
+ yield extension.awaitMessage("content-script-ready");
+ yield extension.awaitMessage("content-script-show");
+
+ // Get the content script context and check that it points to the correct window.
+
+ let {DocumentManager} = SpecialPowers.Cu.import("resource://gre/modules/ExtensionContent.jsm", {});
+ let context = DocumentManager.getContentScriptContext(extension, win);
+ ok(context != null, "Got content script context");
+
+ is(SpecialPowers.unwrap(context.contentWindow), win, "Context's contentWindow property is correct");
+
+ // Navigate so that the content page is hidden in the bfcache.
+
+ win.location = "http://example.org/";
+ yield extension.awaitMessage("content-script-hide");
+
+ is(context.contentWindow, null, "Context's contentWindow property is null");
+
+ // Navigate back so the content page is resurrected from the bfcache.
+
+ SpecialPowers.wrap(win).history.back();
+ yield extension.awaitMessage("content-script-show");
+
+ is(SpecialPowers.unwrap(context.contentWindow), win, "Context's contentWindow property is correct");
+
+ win.close();
+
+ yield extension.awaitMessage("content-script-hide");
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html
new file mode 100644
index 000000000..8aac3e213
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html
@@ -0,0 +1,165 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<!-- WORKAROUND: this textarea hack is used to contain the html page source without escaping it -->
+<textarea id="test-asset">
+ <!DOCTYPE HTML>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <script type="text/javascript" src="content_script_iframe.js"></script>
+ </head>
+ </html>
+</textarea>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript_create_iframe() {
+ function background() {
+ browser.runtime.onMessage.addListener((msg, sender) => {
+ let {name, availableAPIs, manifest, testGetManifest} = msg;
+ let hasExtTabsAPI = availableAPIs.indexOf("tabs") > 0;
+ let hasExtWindowsAPI = availableAPIs.indexOf("windows") > 0;
+
+ browser.test.assertFalse(hasExtTabsAPI, "the created iframe should not be able to use privileged APIs (tabs)");
+ browser.test.assertFalse(hasExtWindowsAPI, "the created iframe should not be able to use privileged APIs (windows)");
+
+ let {applications: {gecko: {id: expectedManifestGeckoId}}} = chrome.runtime.getManifest();
+ let {applications: {gecko: {id: actualManifestGeckoId}}} = manifest;
+
+ browser.test.assertEq(actualManifestGeckoId, expectedManifestGeckoId,
+ "the add-on manifest should be accessible from the created iframe"
+ );
+
+ let {applications: {gecko: {id: testGetManifestGeckoId}}} = testGetManifest;
+
+ browser.test.assertEq(testGetManifestGeckoId, expectedManifestGeckoId,
+ "GET_MANIFEST() returns manifest data before extension unload"
+ );
+
+ browser.test.sendMessage(name);
+ });
+ }
+
+ function contentScript() {
+ let iframe = document.createElement("iframe");
+ iframe.setAttribute("src", browser.runtime.getURL("content_script_iframe.html"));
+ document.body.appendChild(iframe);
+ }
+
+ function contentScriptIframe() {
+ window.GET_MANIFEST = browser.runtime.getManifest.bind(null);
+
+ window.testGetManifestException = () => {
+ try {
+ window.GET_MANIFEST();
+ } catch (exception) {
+ return String(exception);
+ }
+ };
+
+ let testGetManifest = window.GET_MANIFEST();
+
+ let manifest = browser.runtime.getManifest();
+ let availableAPIs = Object.keys(browser);
+
+ browser.runtime.sendMessage({
+ name: "content-script-iframe-loaded",
+ availableAPIs,
+ manifest,
+ testGetManifest,
+ });
+ }
+
+ const ID = "contentscript@tests.mozilla.org";
+ let extensionData = {
+ manifest: {
+ applications: {gecko: {id: ID}},
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ },
+ ],
+ web_accessible_resources: [
+ "content_script_iframe.html",
+ ],
+ },
+
+ background,
+
+ files: {
+ "content_script.js": contentScript,
+ "content_script_iframe.html": document.querySelector("#test-asset").textContent,
+ "content_script_iframe.js": contentScriptIframe,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ let contentScriptIframeCreatedPromise = new Promise(resolve => {
+ extension.onMessage("content-script-iframe-loaded", () => { resolve(); });
+ });
+
+ yield extension.startup();
+ info("extension loaded");
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), contentScriptIframeCreatedPromise]);
+ info("content script privileged iframe loaded and executed");
+
+ info("testing APIs availability once the extension is unloaded...");
+
+ let iframeWindow = SpecialPowers.wrap(win)[0];
+
+ ok(iframeWindow, "content script enabled iframe found");
+ ok(/content_script_iframe\.html$/.test(iframeWindow.location), "the found iframe has the expected URL");
+
+ yield extension.unload();
+ info("extension unloaded");
+
+ info("test content script APIs not accessible from the frame once the extension is unloaded");
+
+ let ww = SpecialPowers.Cu.waiveXrays(iframeWindow);
+ let isDeadWrapper = SpecialPowers.Cu.isDeadWrapper(ww.browser);
+ ok(!isDeadWrapper, "the API object should not be a dead object");
+
+ let manifest;
+ let manifestException;
+
+ try {
+ manifest = ww.browser.runtime.getManifest();
+ } catch (e) {
+ manifestException = e;
+ }
+
+ ok(!manifest, "manifest should be undefined");
+
+ is(String(manifestException), "TypeError: ww.browser.runtime is undefined",
+ "expected exception received");
+
+ let getManifestException = ww.testGetManifestException();
+
+ is(getManifestException, "TypeError: can't access dead object",
+ "expected exception received");
+
+ win.close();
+
+ info("done");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html
new file mode 100644
index 000000000..5630a1d68
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html
@@ -0,0 +1,48 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_content_script_css() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "css": ["content.css"],
+ }],
+ },
+
+ files: {
+ "content.css": "body { max-width: 42px; }",
+ },
+ });
+
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield waitForLoad(win);
+
+ let style = win.getComputedStyle(win.document.body);
+ is(style.maxWidth, "42px", "Stylesheet correctly applied");
+
+ yield extension.unload();
+
+ style = win.getComputedStyle(win.document.body);
+ is(style.maxWidth, "none", "Stylesheet correctly removed");
+
+ win.close();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html
new file mode 100644
index 000000000..137a3cda4
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html
@@ -0,0 +1,81 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for Sandbox metadata on WebExtensions ContentScripts</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript_devtools_sandbox_metadata() {
+ function contentScript() {
+ browser.runtime.sendMessage("contentScript.executed");
+ }
+
+ function background() {
+ browser.runtime.onMessage.addListener((msg) => {
+ if (msg == "contentScript.executed") {
+ browser.test.notifyPass("contentScript.executed");
+ }
+ });
+ }
+
+ let extensionData = {
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ },
+ ],
+ },
+
+ background,
+ files: {
+ "content_script.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ let innerWindowID = SpecialPowers.wrap(win)
+ .QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
+ .getInterface(SpecialPowers.Ci.nsIDOMWindowUtils)
+ .currentInnerWindowID;
+
+ yield extension.awaitFinish("contentScript.executed");
+
+ const {ExtensionContent} = SpecialPowers.Cu.import(
+ "resource://gre/modules/ExtensionContent.jsm", {}
+ );
+
+ let res = ExtensionContent.getContentScriptGlobalsForWindow(win);
+ is(res.length, 1, "Got the expected array of globals");
+ let metadata = SpecialPowers.Cu.getSandboxMetadata(res[0]) || {};
+
+ is(metadata.addonId, extension.id, "Got the expected addonId");
+ is(metadata["inner-window-id"], innerWindowID, "Got the expected inner-window-id");
+
+ yield extension.unload();
+ info("extension unloaded");
+
+ res = ExtensionContent.getContentScriptGlobalsForWindow(win);
+ is(res.length, 0, "No content scripts globals found once the extension is unloaded");
+
+ win.close();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html
new file mode 100644
index 000000000..f3414901d
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html
@@ -0,0 +1,95 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+add_task(function* test_contentscript_exportHelpers() {
+ function contentScript() {
+ browser.test.assertTrue(typeof cloneInto === "function");
+ browser.test.assertTrue(typeof createObjectIn === "function");
+ browser.test.assertTrue(typeof exportFunction === "function");
+
+ /* globals exportFunction, precisePi, reportPi */
+ let value = 3.14;
+ exportFunction(() => value, window, {defineAs: "precisePi"});
+
+ browser.test.assertEq("undefined", typeof precisePi,
+ "exportFunction should export to the page's scope only");
+
+ browser.test.assertEq("undefined", typeof window.precisePi,
+ "exportFunction should export to the page's scope only");
+
+ let results = [];
+ exportFunction(pi => results.push(pi), window, {defineAs: "reportPi"});
+
+ let s = document.createElement("script");
+ s.textContent = `(${function() {
+ let result1 = "unknown 1";
+ let result2 = "unknown 2";
+ try {
+ result1 = precisePi();
+ } catch (e) {
+ result1 = "err:" + e;
+ }
+ try {
+ result2 = window.precisePi();
+ } catch (e) {
+ result2 = "err:" + e;
+ }
+ reportPi(result1);
+ reportPi(result2);
+ }})();`;
+
+ document.documentElement.appendChild(s);
+ // Inline script ought to run synchronously.
+
+ browser.test.assertEq(3.14, results[0],
+ "exportFunction on window should define a global function");
+ browser.test.assertEq(3.14, results[1],
+ "exportFunction on window should export a property to window.");
+
+ browser.test.assertEq(2, results.length,
+ "Expecting the number of results to match the number of method calls");
+
+ browser.test.notifyPass("export helper test completed");
+ }
+
+ let extensionData = {
+ manifest: {
+ content_scripts: [{
+ js: ["contentscript.js"],
+ matches: ["http://mochi.test/*/file_sample.html"],
+ run_at: "document_start",
+ }],
+ },
+
+ files: {
+ "contentscript.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield extension.awaitFinish("export helper test completed");
+ win.close();
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html
new file mode 100644
index 000000000..a2f38dce6
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html
@@ -0,0 +1,89 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script private browsing ID</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript_incognito() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ },
+ ],
+ },
+
+ background() {
+ let windowId;
+
+ browser.test.onMessage.addListener(([msg, url]) => {
+ if (msg === "open-window") {
+ browser.windows.create({url, incognito: true}).then(window => {
+ windowId = window.id;
+ });
+ } else if (msg === "close-window") {
+ browser.windows.remove(windowId).then(() => {
+ browser.test.sendMessage("done");
+ });
+ }
+ });
+ },
+
+ files: {
+ "content_script.js": async () => {
+ const COOKIE = "foo=florgheralzps";
+ document.cookie = COOKIE;
+
+ let url = new URL("return_headers.sjs", location.href);
+
+ let responses = [
+ new Promise(resolve => {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.onload = () => resolve(JSON.parse(xhr.responseText));
+ xhr.send();
+ }),
+
+ fetch(url, {credentials: "include"}).then(body => body.json()),
+ ];
+
+ try {
+ for (let response of await Promise.all(responses)) {
+ browser.test.assertEq(COOKIE, response.cookie, "Got expected cookie header");
+ }
+ browser.test.notifyPass("cookies");
+ } catch (e) {
+ browser.test.fail(`Error: ${e}`);
+ browser.test.notifyFail("cookies");
+ }
+ },
+ },
+ });
+
+ yield extension.startup();
+
+ extension.sendMessage(["open-window", SimpleTest.getTestFileURL("file_sample.html")]);
+
+ yield extension.awaitFinish("cookies");
+
+ extension.sendMessage(["close-window"]);
+ yield extension.awaitMessage("done");
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
+
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html
new file mode 100644
index 000000000..eaf815092
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html
@@ -0,0 +1,59 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript() {
+ function background() {
+ browser.test.onMessage.addListener(url => {
+ browser.tabs.create({url}).then(tab => {
+ return browser.tabs.executeScript(tab.id, {code: "true;"})
+ .then(() => {
+ browser.test.sendMessage("executed", true);
+ browser.tabs.remove([tab.id]);
+ }, err => {
+ browser.test.sendMessage("executed", false);
+ browser.tabs.remove([tab.id]);
+ });
+ });
+ });
+ }
+
+ let extensionData = {
+ manifest: {
+ permissions: ["<all_urls>"],
+ },
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ extension.sendMessage("https://example.com");
+ let result = yield extension.awaitMessage("executed");
+ is(result, true, "Content script can be run in a page without mozAddonManager");
+
+ yield SpecialPowers.pushPrefEnv({
+ set: [["extensions.webapi.testing", true]],
+ });
+
+ extension.sendMessage("https://example.com");
+ result = yield extension.awaitMessage("executed");
+ is(result, false, "Content script cannot be run in a page with mozAddonManager");
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html
new file mode 100644
index 000000000..33a8c4ccc
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html
@@ -0,0 +1,96 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script teardown</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+add_task(function* test_contentscript_reload_and_unload() {
+ function contentScript() {
+ browser.test.sendMessage("contentscript-run");
+ }
+ function background() {
+ let removedTabs = 0;
+ browser.tabs.onRemoved.addListener(() => {
+ browser.test.assertEq(1, ++removedTabs,
+ "Expected only one tab to be removed during the test");
+ browser.test.sendMessage("tab-closed");
+ });
+ }
+
+ let extensionData = {
+ background,
+ manifest: {
+ content_scripts: [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["contentscript.js"],
+ }],
+ },
+
+ files: {
+ "contentscript.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let chromeScript = SpecialPowers.loadChromeScript(
+ SimpleTest.getTestFileURL("file_teardown_test.js"));
+ yield chromeScript.promiseOneMessage("chromescript-startup");
+ function* getContextEvents() {
+ chromeScript.sendAsyncMessage("get-context-events");
+ let contextEvents = yield chromeScript.promiseOneMessage("context-events");
+ return contextEvents.filter(event => event.extensionId == extension.id);
+ }
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitMessage("contentscript-run");
+ let tabUrl = win.location.href;
+
+ let contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1,
+ "ExtensionContext state change after loading a content script");
+ is(contextEvents[0].eventType, "load",
+ "Create ExtensionContext for content script");
+ is(contextEvents[0].url, tabUrl, "ExtensionContext URL = page");
+
+ let promiseReload = extension.awaitMessage("contentscript-run");
+ win.location.reload();
+ yield promiseReload;
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 2,
+ "ExtensionContext state changes after reloading a content script");
+ is(contextEvents[0].eventType, "unload", "Unload old ExtensionContext");
+ is(contextEvents[0].url, tabUrl, "ExtensionContext URL = page");
+ is(contextEvents[1].eventType, "load",
+ "Create new ExtensionContext for content script");
+ is(contextEvents[1].url, tabUrl, "ExtensionContext URL = page");
+
+ let tabClosePromise = extension.awaitMessage("tab-closed");
+ win.close();
+ yield tabClosePromise;
+
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1,
+ "ExtensionContext state change after unloading a content script");
+ is(contextEvents[0].eventType, "unload",
+ "Unload ExtensionContext after closing the tab with the content script");
+ is(contextEvents[0].url, tabUrl, "ExtensionContext URL = page");
+
+ chromeScript.sendAsyncMessage("cleanup");
+ chromeScript.destroy();
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html
new file mode 100644
index 000000000..d414a4e46
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html
@@ -0,0 +1,234 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_cookies() {
+ async function background() {
+ function assertExpected(expected, cookie) {
+ for (let key of Object.keys(cookie)) {
+ browser.test.assertTrue(key in expected, `found property ${key}`);
+ browser.test.assertEq(expected[key], cookie[key], `property value for ${key} is correct`);
+ }
+ browser.test.assertEq(Object.keys(expected).length, Object.keys(cookie).length, "all expected properties found");
+ }
+
+ const TEST_URL = "http://example.org/";
+ const TEST_SECURE_URL = "https://example.org/";
+ const THE_FUTURE = Date.now() + 5 * 60;
+ const TEST_PATH = "set_path";
+ const TEST_URL_WITH_PATH = TEST_URL + TEST_PATH;
+ const TEST_COOKIE_PATH = `/${TEST_PATH}`;
+ const STORE_ID = "firefox-default";
+ const PRIVATE_STORE_ID = "firefox-private";
+
+ let expected = {
+ name: "name1",
+ value: "value1",
+ domain: "example.org",
+ hostOnly: true,
+ path: "/",
+ secure: false,
+ httpOnly: false,
+ session: false,
+ expirationDate: THE_FUTURE,
+ storeId: STORE_ID,
+ };
+
+ let cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", expirationDate: THE_FUTURE});
+ assertExpected(expected, cookie);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
+ assertExpected(expected, cookie);
+
+ let cookies = await browser.cookies.getAll({name: "name1"});
+ browser.test.assertEq(cookies.length, 1, "one cookie found for matching name");
+ assertExpected(expected, cookies[0]);
+
+ cookies = await browser.cookies.getAll({domain: "example.org"});
+ browser.test.assertEq(cookies.length, 1, "one cookie found for matching domain");
+ assertExpected(expected, cookies[0]);
+
+ cookies = await browser.cookies.getAll({domain: "example.net"});
+ browser.test.assertEq(cookies.length, 0, "no cookies found for non-matching domain");
+
+ cookies = await browser.cookies.getAll({secure: false});
+ browser.test.assertEq(cookies.length, 1, "one non-secure cookie found");
+ assertExpected(expected, cookies[0]);
+
+ cookies = await browser.cookies.getAll({secure: true});
+ browser.test.assertEq(cookies.length, 0, "no secure cookies found");
+
+ cookies = await browser.cookies.getAll({storeId: STORE_ID});
+ browser.test.assertEq(cookies.length, 1, "one cookie found for valid storeId");
+ assertExpected(expected, cookies[0]);
+
+ cookies = await browser.cookies.getAll({storeId: "invalid_id"});
+ browser.test.assertEq(cookies.length, 0, "no cookies found for invalid storeId");
+
+ let details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
+ assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
+ browser.test.assertEq(null, cookie, "removed cookie not found");
+
+ let stores = await browser.cookies.getAllCookieStores();
+ browser.test.assertEq(1, stores.length, "expected number of stores returned");
+ browser.test.assertEq(STORE_ID, stores[0].id, "expected store id returned");
+ browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for store");
+
+ {
+ let privateWindow = await browser.windows.create({incognito: true});
+ let stores = await browser.cookies.getAllCookieStores();
+
+ browser.test.assertEq(2, stores.length, "expected number of stores returned");
+ browser.test.assertEq(STORE_ID, stores[0].id, "expected store id returned");
+ browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for store");
+ browser.test.assertEq(PRIVATE_STORE_ID, stores[1].id, "expected private store id returned");
+ browser.test.assertEq(1, stores[0].tabIds.length, "one tab returned for private store");
+
+ await browser.windows.remove(privateWindow.id);
+ }
+
+ cookie = await browser.cookies.set({url: TEST_URL, name: "name2", domain: ".example.org", expirationDate: THE_FUTURE});
+ browser.test.assertEq(false, cookie.hostOnly, "cookie is not a hostOnly cookie");
+
+ details = await browser.cookies.remove({url: TEST_URL, name: "name2"});
+ assertExpected({url: TEST_URL, name: "name2", storeId: STORE_ID}, details);
+
+ // Create a session cookie.
+ cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1"});
+ browser.test.assertEq(true, cookie.session, "session cookie set");
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
+ browser.test.assertEq(true, cookie.session, "got session cookie");
+
+ cookies = await browser.cookies.getAll({session: true});
+ browser.test.assertEq(cookies.length, 1, "one session cookie found");
+ browser.test.assertEq(true, cookies[0].session, "found session cookie");
+
+ cookies = await browser.cookies.getAll({session: false});
+ browser.test.assertEq(cookies.length, 0, "no non-session cookies found");
+
+ details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
+ assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
+ browser.test.assertEq(null, cookie, "removed cookie not found");
+
+ cookie = await browser.cookies.set({url: TEST_SECURE_URL, name: "name1", value: "value1", secure: true});
+ browser.test.assertEq(true, cookie.secure, "secure cookie set");
+
+ cookie = await browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
+ browser.test.assertEq(true, cookie.session, "got secure cookie");
+
+ cookies = await browser.cookies.getAll({secure: true});
+ browser.test.assertEq(cookies.length, 1, "one secure cookie found");
+ browser.test.assertEq(true, cookies[0].secure, "found secure cookie");
+
+ cookies = await browser.cookies.getAll({secure: false});
+ browser.test.assertEq(cookies.length, 0, "no non-secure cookies found");
+
+ details = await browser.cookies.remove({url: TEST_SECURE_URL, name: "name1"});
+ assertExpected({url: TEST_SECURE_URL, name: "name1", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.get({url: TEST_SECURE_URL, name: "name1"});
+ browser.test.assertEq(null, cookie, "removed cookie not found");
+
+ cookie = await browser.cookies.set({url: TEST_URL_WITH_PATH, path: TEST_COOKIE_PATH, name: "name1", value: "value1", expirationDate: THE_FUTURE});
+ browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "created cookie with path");
+
+ cookie = await browser.cookies.get({url: TEST_URL_WITH_PATH, name: "name1"});
+ browser.test.assertEq(TEST_COOKIE_PATH, cookie.path, "got cookie with path");
+
+ cookies = await browser.cookies.getAll({path: TEST_COOKIE_PATH});
+ browser.test.assertEq(cookies.length, 1, "one cookie with path found");
+ browser.test.assertEq(TEST_COOKIE_PATH, cookies[0].path, "found cookie with path");
+
+ cookie = await browser.cookies.get({url: TEST_URL + "invalid_path", name: "name1"});
+ browser.test.assertEq(null, cookie, "get with invalid path returns null");
+
+ cookies = await browser.cookies.getAll({path: "/invalid_path"});
+ browser.test.assertEq(cookies.length, 0, "getAll with invalid path returns 0 cookies");
+
+ details = await browser.cookies.remove({url: TEST_URL_WITH_PATH, name: "name1"});
+ assertExpected({url: TEST_URL_WITH_PATH, name: "name1", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: true});
+ browser.test.assertEq(true, cookie.httpOnly, "httpOnly cookie set");
+
+ cookie = await browser.cookies.set({url: TEST_URL, name: "name1", value: "value1", httpOnly: false});
+ browser.test.assertEq(false, cookie.httpOnly, "non-httpOnly cookie set");
+
+ details = await browser.cookies.remove({url: TEST_URL, name: "name1"});
+ assertExpected({url: TEST_URL, name: "name1", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.set({url: TEST_URL});
+ browser.test.assertEq("", cookie.name, "default name set");
+ browser.test.assertEq("", cookie.value, "default value set");
+ browser.test.assertEq(true, cookie.session, "no expiry date created session cookie");
+
+ {
+ let privateWindow = await browser.windows.create({incognito: true});
+
+ // Hacky work-around for bugzil.la/1309637
+ await new Promise(resolve => setTimeout(resolve, 700));
+
+ let cookie = await browser.cookies.set({url: TEST_URL, name: "store", value: "private", expirationDate: THE_FUTURE, storeId: PRIVATE_STORE_ID});
+ browser.test.assertEq("private", cookie.value, "set the private cookie");
+
+ cookie = await browser.cookies.set({url: TEST_URL, name: "store", value: "default", expirationDate: THE_FUTURE, storeId: STORE_ID});
+ browser.test.assertEq("default", cookie.value, "set the default cookie");
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
+ browser.test.assertEq("private", cookie.value, "get the private cookie");
+ browser.test.assertEq(PRIVATE_STORE_ID, cookie.storeId, "get the private cookie storeId");
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
+ browser.test.assertEq("default", cookie.value, "get the default cookie");
+ browser.test.assertEq(STORE_ID, cookie.storeId, "get the default cookie storeId");
+
+ let details = await browser.cookies.remove({url: TEST_URL, name: "store", storeId: STORE_ID});
+ assertExpected({url: TEST_URL, name: "store", storeId: STORE_ID}, details);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: STORE_ID});
+ browser.test.assertEq(null, cookie, "deleted the default cookie");
+
+ details = await browser.cookies.remove({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
+ assertExpected({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID}, details);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "store", storeId: PRIVATE_STORE_ID});
+ browser.test.assertEq(null, cookie, "deleted the private cookie");
+
+ await browser.windows.remove(privateWindow.id);
+ }
+
+ browser.test.notifyPass("cookies");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["cookies", "*://example.org/"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("cookies");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html
new file mode 100644
index 000000000..bc4994eec
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html
@@ -0,0 +1,93 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* setup() {
+ // make sure userContext is enabled.
+ return SpecialPowers.pushPrefEnv({"set": [
+ ["privacy.userContext.enabled", true],
+ ]});
+});
+
+add_task(function* test_cookie_containers() {
+ async function background() {
+ function assertExpected(expected, cookie) {
+ for (let key of Object.keys(cookie)) {
+ browser.test.assertTrue(key in expected, `found property ${key}`);
+ browser.test.assertEq(expected[key], cookie[key], `property value for ${key} is correct`);
+ }
+ browser.test.assertEq(Object.keys(expected).length, Object.keys(cookie).length, "all expected properties found");
+ }
+
+ const TEST_URL = "http://example.org/";
+ const THE_FUTURE = Date.now() + 5 * 60;
+
+ let expected = {
+ name: "name1",
+ value: "value1",
+ domain: "example.org",
+ hostOnly: true,
+ path: "/",
+ secure: false,
+ httpOnly: false,
+ session: false,
+ expirationDate: THE_FUTURE,
+ storeId: "firefox-container-1",
+ };
+
+ let cookie = await browser.cookies.set({
+ url: TEST_URL, name: "name1", value: "value1",
+ expirationDate: THE_FUTURE, storeId: "firefox-container-1",
+ });
+ browser.test.assertEq("firefox-container-1", cookie.storeId, "the cookie has the correct storeId");
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1"});
+ browser.test.assertEq(null, cookie, "get() without storeId returns null");
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
+ assertExpected(expected, cookie);
+
+ let cookies = await browser.cookies.getAll({storeId: "firefox-default"});
+ browser.test.assertEq(0, cookies.length, "getAll() with default storeId returns an empty array");
+
+ cookies = await browser.cookies.getAll({storeId: "firefox-container-1"});
+ browser.test.assertEq(1, cookies.length, "one cookie found for matching domain");
+ assertExpected(expected, cookies[0]);
+
+ let details = await browser.cookies.remove({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
+ assertExpected({url: TEST_URL, name: "name1", storeId: "firefox-container-1"}, details);
+
+ cookie = await browser.cookies.get({url: TEST_URL, name: "name1", storeId: "firefox-container-1"});
+ browser.test.assertEq(null, cookie, "removed cookie not found");
+
+ browser.test.notifyPass("cookies");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["cookies", "*://example.org/"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("cookies");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html
new file mode 100644
index 000000000..3927d9e94
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html
@@ -0,0 +1,72 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_cookies_expiry() {
+ function background() {
+ let expectedEvents = [];
+
+ browser.cookies.onChanged.addListener(event => {
+ expectedEvents.push(`${event.removed}:${event.cause}`);
+ if (expectedEvents.length === 1) {
+ browser.test.assertEq("true:expired", expectedEvents[0], "expired cookie removed");
+ browser.test.assertEq("first", event.cookie.name, "expired cookie has the expected name");
+ browser.test.assertEq("one", event.cookie.value, "expired cookie has the expected value");
+ } else {
+ browser.test.assertEq("false:explicit", expectedEvents[1], "new cookie added");
+ browser.test.assertEq("first", event.cookie.name, "new cookie has the expected name");
+ browser.test.assertEq("one-again", event.cookie.value, "new cookie has the expected value");
+ browser.test.notifyPass("cookie-expiry");
+ }
+ });
+
+ setTimeout(() => {
+ browser.test.sendMessage("change-cookies");
+ }, 1000);
+ }
+
+ let domain = ".example.com";
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "permissions": ["http://example.com/", "cookies"],
+ },
+ background,
+ });
+
+ let cookieSvc = SpecialPowers.Services.cookies;
+
+ let cookie = {
+ host: domain,
+ name: "first",
+ path: "/",
+ };
+
+ do {
+ cookieSvc.add(cookie.host, cookie.path, cookie.name, "one", false, false, false, Date.now() / 1000 + 1);
+ } while (!cookieSvc.cookieExists(cookie));
+
+ yield extension.startup();
+ yield extension.awaitMessage("change-cookies");
+
+ cookieSvc.add(cookie.host, cookie.path, cookie.name, "one-again", false, false, false, Date.now() / 1000 + 10);
+
+ yield extension.awaitFinish("cookie-expiry");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html
new file mode 100644
index 000000000..15a62855a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html
@@ -0,0 +1,112 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <script type="text/javascript" src="head_cookies.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* init() {
+ // We need to trigger a cookie eviction in order to test our batch delete
+ // observer.
+ SpecialPowers.setIntPref("network.cookie.maxPerHost", 3);
+ SimpleTest.registerCleanupFunction(() => {
+ SpecialPowers.clearUserPref("network.cookie.maxPerHost");
+ });
+});
+
+add_task(function* test_bad_cookie_permissions() {
+ info("Test non-matching, non-secure domain with non-secure cookie");
+ yield testCookies({
+ permissions: ["http://example.com/", "cookies"],
+ url: "http://example.net/",
+ domain: "example.net",
+ secure: false,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+
+ info("Test non-matching, secure domain with non-secure cookie");
+ yield testCookies({
+ permissions: ["https://example.com/", "cookies"],
+ url: "https://example.net/",
+ domain: "example.net",
+ secure: false,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+
+ info("Test non-matching, secure domain with secure cookie");
+ yield testCookies({
+ permissions: ["https://example.com/", "cookies"],
+ url: "https://example.net/",
+ domain: "example.net",
+ secure: false,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+
+ info("Test matching subdomain with superdomain privileges, secure cookie (http)");
+ yield testCookies({
+ permissions: ["http://foo.bar.example.com/", "cookies"],
+ url: "http://foo.bar.example.com/",
+ domain: ".example.com",
+ secure: true,
+ shouldPass: false,
+ shouldWrite: true,
+ });
+
+ info("Test matching, non-secure domain with secure cookie");
+ yield testCookies({
+ permissions: ["http://example.com/", "cookies"],
+ url: "http://example.com/",
+ domain: "example.com",
+ secure: true,
+ shouldPass: false,
+ shouldWrite: true,
+ });
+
+ info("Test matching, non-secure host, secure URL");
+ yield testCookies({
+ permissions: ["http://example.com/", "cookies"],
+ url: "https://example.com/",
+ domain: "example.com",
+ secure: true,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+
+ info("Test non-matching domain");
+ yield testCookies({
+ permissions: ["http://example.com/", "cookies"],
+ url: "http://example.com/",
+ domain: "example.net",
+ secure: false,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+
+ info("Test invalid scheme");
+ yield testCookies({
+ permissions: ["ftp://example.com/", "cookies"],
+ url: "ftp://example.com/",
+ domain: "example.com",
+ secure: false,
+ shouldPass: false,
+ shouldWrite: false,
+ });
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html
new file mode 100644
index 000000000..31e83188c
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html
@@ -0,0 +1,86 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <script type="text/javascript" src="head_cookies.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* init() {
+ // We need to trigger a cookie eviction in order to test our batch delete
+ // observer.
+ SpecialPowers.setIntPref("network.cookie.maxPerHost", 3);
+ SimpleTest.registerCleanupFunction(() => {
+ SpecialPowers.clearUserPref("network.cookie.maxPerHost");
+ });
+});
+
+add_task(function* test_good_cookie_permissions() {
+ info("Test matching, non-secure domain with non-secure cookie");
+ yield testCookies({
+ permissions: ["http://example.com/", "cookies"],
+ url: "http://example.com/",
+ domain: "example.com",
+ secure: false,
+ shouldPass: true,
+ });
+
+ info("Test matching, secure domain with non-secure cookie");
+ yield testCookies({
+ permissions: ["https://example.com/", "cookies"],
+ url: "https://example.com/",
+ domain: "example.com",
+ secure: false,
+ shouldPass: true,
+ });
+
+ info("Test matching, secure domain with secure cookie");
+ yield testCookies({
+ permissions: ["https://example.com/", "cookies"],
+ url: "https://example.com/",
+ domain: "example.com",
+ secure: true,
+ shouldPass: true,
+ });
+
+ info("Test matching subdomain with superdomain privileges, secure cookie (https)");
+ yield testCookies({
+ permissions: ["https://foo.bar.example.com/", "cookies"],
+ url: "https://foo.bar.example.com/",
+ domain: ".example.com",
+ secure: true,
+ shouldPass: true,
+ });
+
+ info("Test matching subdomain with superdomain privileges, non-secure cookie (https)");
+ yield testCookies({
+ permissions: ["https://foo.bar.example.com/", "cookies"],
+ url: "https://foo.bar.example.com/",
+ domain: ".example.com",
+ secure: false,
+ shouldPass: true,
+ });
+
+ info("Test matching subdomain with superdomain privileges, non-secure cookie (http)");
+ yield testCookies({
+ permissions: ["http://foo.bar.example.com/", "cookies"],
+ url: "http://foo.bar.example.com/",
+ domain: ".example.com",
+ secure: false,
+ shouldPass: true,
+ });
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html b/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html
new file mode 100644
index 000000000..640522b40
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html
@@ -0,0 +1,92 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_contentscript() {
+ function background() {
+ browser.runtime.onMessage.addListener(([script], sender) => {
+ browser.test.sendMessage("run", {script});
+ browser.test.sendMessage("run-" + script);
+ });
+ browser.test.sendMessage("running");
+ }
+
+ function contentScriptAll() {
+ browser.runtime.sendMessage(["all"]);
+ }
+ function contentScriptIncludesTest1() {
+ browser.runtime.sendMessage(["includes-test1"]);
+ }
+ function contentScriptExcludesTest1() {
+ browser.runtime.sendMessage(["excludes-test1"]);
+ }
+
+ let extensionData = {
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://example.org/", "http://*.example.org/"],
+ "exclude_globs": [],
+ "include_globs": ["*"],
+ "js": ["content_script_all.js"],
+ },
+ {
+ "matches": ["http://example.org/", "http://*.example.org/"],
+ "include_globs": ["*test1*"],
+ "js": ["content_script_includes_test1.js"],
+ },
+ {
+ "matches": ["http://example.org/", "http://*.example.org/"],
+ "exclude_globs": ["*test1*"],
+ "js": ["content_script_excludes_test1.js"],
+ },
+ ],
+ },
+ background,
+
+ files: {
+ "content_script_all.js": contentScriptAll,
+ "content_script_includes_test1.js": contentScriptIncludesTest1,
+ "content_script_excludes_test1.js": contentScriptExcludesTest1,
+ },
+
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ let ran = 0;
+ extension.onMessage("run", ({script}) => {
+ ran++;
+ });
+
+ yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
+ info("extension loaded");
+
+ let win = window.open("http://example.org/");
+ yield Promise.all([extension.awaitMessage("run-all"), extension.awaitMessage("run-excludes-test1")]);
+ win.close();
+ is(ran, 2);
+
+ win = window.open("http://test1.example.org/");
+ yield Promise.all([extension.awaitMessage("run-all"), extension.awaitMessage("run-includes-test1")]);
+ win.close();
+ is(ran, 4);
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_generate.html b/toolkit/components/webextensions/test/mochitest/test_ext_generate.html
new file mode 100644
index 000000000..cfafcbad9
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_generate.html
@@ -0,0 +1,49 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for generating WebExtensions</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.test.log("running background script");
+
+ browser.test.onMessage.addListener((x, y) => {
+ browser.test.assertEq(x, 10, "x is 10");
+ browser.test.assertEq(y, 20, "y is 20");
+
+ browser.test.notifyPass("background test passed");
+ });
+
+ browser.test.sendMessage("running", 1);
+}
+
+let extensionData = {
+ background,
+};
+
+add_task(function* test_background() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ info("load complete");
+ let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
+ is(x, 1, "got correct value from extension");
+ info("startup complete");
+ extension.sendMessage(10, 20);
+ yield extension.awaitFinish();
+ info("test complete");
+ yield extension.unload();
+ info("extension unloaded successfully");
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html b/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html
new file mode 100644
index 000000000..6e39c2f5d
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html
@@ -0,0 +1,72 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.runtime.onMessage.addListener(([url1, url2]) => {
+ let url3 = browser.runtime.getURL("test_file.html");
+ let url4 = browser.extension.getURL("test_file.html");
+
+ browser.test.assertTrue(url1 !== undefined, "url1 defined");
+
+ browser.test.assertTrue(url1.startsWith("moz-extension://"), "url1 has correct scheme");
+ browser.test.assertTrue(url1.endsWith("test_file.html"), "url1 has correct leaf name");
+
+ browser.test.assertEq(url1, url2, "url2 matches");
+ browser.test.assertEq(url1, url3, "url3 matches");
+ browser.test.assertEq(url1, url4, "url4 matches");
+
+ browser.test.notifyPass("geturl");
+ });
+}
+
+function contentScript() {
+ let url1 = browser.runtime.getURL("test_file.html");
+ let url2 = browser.extension.getURL("test_file.html");
+ browser.runtime.sendMessage([url1, url2]);
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), extension.awaitFinish("geturl")]);
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html b/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html
new file mode 100644
index 000000000..1f7330bbb
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html
@@ -0,0 +1,432 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Test for WebExtension localization APIs</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+SimpleTest.registerCleanupFunction(() => { SpecialPowers.clearUserPref("intl.accept_languages"); });
+SimpleTest.registerCleanupFunction(() => { SpecialPowers.clearUserPref("general.useragent.locale"); });
+
+add_task(function* test_i18n() {
+ function runTests(assertEq) {
+ let _ = browser.i18n.getMessage.bind(browser.i18n);
+
+ let url = browser.runtime.getURL("/");
+ assertEq(url, `moz-extension://${_("@@extension_id")}/`, "@@extension_id builtin message");
+
+ assertEq("Foo.", _("Foo"), "Simple message in selected locale.");
+
+ assertEq("(bar)", _("bar"), "Simple message fallback in default locale.");
+
+ assertEq("", _("some-unknown-locale-string"), "Unknown locale string.");
+
+ assertEq("", _("@@unknown_builtin_string"), "Unknown built-in string.");
+ assertEq("", _("@@bidi_unknown_builtin_string"), "Unknown built-in bidi string.");
+
+ assertEq("Føo.", _("Föo"), "Multi-byte message in selected locale.");
+
+ let substitutions = [];
+ substitutions[4] = "5";
+ substitutions[13] = "14";
+
+ assertEq("'$0' '14' '' '5' '$$$$' '$'.", _("basic_substitutions", substitutions),
+ "Basic numeric substitutions");
+
+ assertEq("'$0' '' 'just a string' '' '$$$$' '$'.", _("basic_substitutions", "just a string"),
+ "Basic numeric substitutions, with non-array value");
+
+ let values = _("named_placeholder_substitutions", ["(subst $1 $2)", "(2 $1 $2)"]).split("\n");
+
+ assertEq("_foo_ (subst $1 $2) _bar_", values[0], "Named and numeric substitution");
+
+ assertEq("(2 $1 $2)", values[1], "Numeric substitution amid named placeholders");
+
+ assertEq("$bad name$", values[2], "Named placeholder with invalid key");
+
+ assertEq("", values[3], "Named placeholder with an invalid value");
+
+ assertEq("Accepted, but shouldn't break.", values[4], "Named placeholder with a strange content value");
+
+ assertEq("$foo", values[5], "Non-placeholder token that should be ignored");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "default_locale": "jp",
+
+ content_scripts: [
+ {"matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content.js"]},
+ ],
+ },
+
+
+ files: {
+ "_locales/en_US/messages.json": {
+ "foo": {
+ "message": "Foo.",
+ "description": "foo",
+ },
+
+ "föo": {
+ "message": "Føo.",
+ "description": "foo",
+ },
+
+ "basic_substitutions": {
+ "message": "'$0' '$14' '$1' '$5' '$$$$$' '$$'.",
+ "description": "foo",
+ },
+
+ "Named_placeholder_substitutions": {
+ "message": "$Foo$\n$2\n$bad name$\n$bad_value$\n$bad_content_value$\n$foo",
+ "description": "foo",
+ "placeholders": {
+ "foO": {
+ "content": "_foo_ $1 _bar_",
+ "description": "foo",
+ },
+
+ "bad name": {
+ "content": "Nope.",
+ "description": "bad name",
+ },
+
+ "bad_value": "Nope.",
+
+ "bad_content_value": {
+ "content": ["Accepted, but shouldn't break."],
+ "description": "bad value",
+ },
+ },
+ },
+
+ "broken_placeholders": {
+ "message": "$broken$",
+ "description": "broken placeholders",
+ "placeholders": "foo.",
+ },
+ },
+
+ "_locales/jp/messages.json": {
+ "foo": {
+ "message": "(foo)",
+ "description": "foo",
+ },
+
+ "bar": {
+ "message": "(bar)",
+ "description": "bar",
+ },
+ },
+
+ "content.js": "new " + function(runTestsFn) {
+ runTestsFn((...args) => {
+ browser.runtime.sendMessage(["assertEq", ...args]);
+ });
+
+ browser.runtime.sendMessage(["content-script-finished"]);
+ } + `(${runTests})`,
+ },
+
+ background: "new " + function(runTestsFn) {
+ browser.runtime.onMessage.addListener(([msg, ...args]) => {
+ if (msg == "assertEq") {
+ browser.test.assertEq(...args);
+ } else {
+ browser.test.sendMessage(msg, ...args);
+ }
+ });
+
+ runTestsFn(browser.test.assertEq.bind(browser.test));
+ } + `(${runTests})`,
+ });
+
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitMessage("content-script-finished");
+ win.close();
+
+ yield extension.unload();
+});
+
+add_task(function* test_get_accept_languages() {
+ function background() {
+ function checkResults(source, results, expected) {
+ browser.test.assertEq(
+ expected.length,
+ results.length,
+ `got expected number of languages in ${source}`);
+ results.forEach((lang, index) => {
+ browser.test.assertEq(
+ expected[index],
+ lang,
+ `got expected language in ${source}`);
+ });
+ }
+
+ let tabId;
+
+ browser.tabs.query({currentWindow: true, active: true}, tabs => {
+ tabId = tabs[0].id;
+ browser.test.sendMessage("ready");
+ });
+
+ browser.test.onMessage.addListener(async ([msg, expected]) => {
+ let contentResults = await browser.tabs.sendMessage(tabId, "get-results");
+ let backgroundResults = await browser.i18n.getAcceptLanguages();
+
+ checkResults("contentScript", contentResults, expected);
+ checkResults("background", backgroundResults, expected);
+
+ browser.test.sendMessage("done");
+ });
+ }
+
+ function content() {
+ browser.runtime.onMessage.addListener((msg, sender, respond) => {
+ browser.i18n.getAcceptLanguages(respond);
+ return true;
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "run_at": "document_start",
+ "js": ["content_script.js"],
+ }],
+ },
+
+ background,
+
+ files: {
+ "content_script.js": content,
+ },
+ });
+
+ let win = window.open("file_sample.html");
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ let expectedLangs = ["en-US", "en"];
+ extension.sendMessage(["expect-results", expectedLangs]);
+ yield extension.awaitMessage("done");
+
+ expectedLangs = ["en-US", "en", "fr-CA", "fr"];
+ SpecialPowers.setCharPref("intl.accept_languages", expectedLangs.toString());
+ extension.sendMessage(["expect-results", expectedLangs]);
+ yield extension.awaitMessage("done");
+ SpecialPowers.clearUserPref("intl.accept_languages");
+
+ win.close();
+
+ yield extension.unload();
+});
+
+add_task(function* test_get_ui_language() {
+ function getResults() {
+ return {
+ getUILanguage: browser.i18n.getUILanguage(),
+ getMessage: browser.i18n.getMessage("@@ui_locale"),
+ };
+ }
+
+ function background(getResultsFn) {
+ function checkResults(source, results, expected) {
+ browser.test.assertEq(
+ expected,
+ results.getUILanguage,
+ `Got expected getUILanguage result in ${source}`
+ );
+ browser.test.assertEq(
+ expected,
+ results.getMessage,
+ `Got expected getMessage result in ${source}`
+ );
+ }
+
+ let tabId;
+
+ browser.test.onMessage.addListener(([msg, expected]) => {
+ browser.tabs.sendMessage(tabId, "get-results", result => {
+ checkResults("contentScript", result, expected);
+ checkResults("background", getResultsFn(), expected);
+
+ browser.test.sendMessage("done");
+ });
+ });
+
+ browser.tabs.query({currentWindow: true, active: true}, tabs => {
+ tabId = tabs[0].id;
+ browser.test.sendMessage("ready");
+ });
+ }
+
+ function content(getResultsFn) {
+ browser.runtime.onMessage.addListener((msg, sender, respond) => {
+ respond(getResultsFn());
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "run_at": "document_start",
+ "js": ["content_script.js"],
+ }],
+ },
+
+ background: `(${background})(${getResults})`,
+
+ files: {
+ "content_script.js": `(${content})(${getResults})`,
+ },
+ });
+
+ let win = window.open("file_sample.html");
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage(["expect-results", "en_US"]);
+ yield extension.awaitMessage("done");
+
+ SpecialPowers.setCharPref("general.useragent.locale", "he");
+
+ extension.sendMessage(["expect-results", "he"]);
+ yield extension.awaitMessage("done");
+
+ win.close();
+
+ yield extension.unload();
+});
+
+
+add_task(function* test_detect_language() {
+ const af_string = " aam skukuza die naam beteken hy wat skoonvee of hy wat alles onderstebo keer wysig " +
+ "bosveldkampe boskampe is kleiner afgeleë ruskampe wat oor min fasiliteite beskik daar is geen restaurante " +
+ "of winkels nie en slegs oornagbesoekers word toegelaat bateleur";
+ // String with intermixed French/English text
+ const fr_en_string = "France is the largest country in Western Europe and the third-largest in Europe as a whole. " +
+ "A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter " +
+ "Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, " +
+ "Pour une aide rapide et effective, veuiller trouver votre aide dans le menu ci-dessus." +
+ "Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog";
+
+ function background() {
+ function checkResult(source, result, expected) {
+ browser.test.assertEq(expected.isReliable, result.isReliable, "result.confident is true");
+ browser.test.assertEq(
+ expected.languages.length,
+ result.languages.length,
+ `result.languages contains the expected number of languages in ${source}`);
+ expected.languages.forEach((lang, index) => {
+ browser.test.assertEq(
+ lang.percentage,
+ result.languages[index].percentage,
+ `element ${index} of result.languages array has the expected percentage in ${source}`);
+ browser.test.assertEq(
+ lang.language,
+ result.languages[index].language,
+ `element ${index} of result.languages array has the expected language in ${source}`);
+ });
+ }
+
+ let tabId;
+
+ browser.tabs.query({currentWindow: true, active: true}, tabs => {
+ tabId = tabs[0].id;
+ browser.test.sendMessage("ready");
+ });
+
+ browser.test.onMessage.addListener(async ([msg, expected]) => {
+ let backgroundResults = await browser.i18n.detectLanguage(msg);
+ let contentResults = await browser.tabs.sendMessage(tabId, msg);
+
+ checkResult("background", backgroundResults, expected);
+ checkResult("contentScript", contentResults, expected);
+
+ browser.test.sendMessage("done");
+ });
+ }
+
+ function content() {
+ browser.runtime.onMessage.addListener((msg, sender, respond) => {
+ browser.i18n.detectLanguage(msg, respond);
+ return true;
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "run_at": "document_start",
+ "js": ["content_script.js"],
+ }],
+ },
+
+ background,
+
+ files: {
+ "content_script.js": content,
+ },
+ });
+
+ let win = window.open("file_sample.html");
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ let expected = {
+ isReliable: true,
+ languages: [
+ {
+ language: "fr",
+ percentage: 67,
+ },
+ {
+ language: "en",
+ percentage: 32,
+ },
+ ],
+ };
+ extension.sendMessage([fr_en_string, expected]);
+ yield extension.awaitMessage("done");
+
+ expected = {
+ isReliable: true,
+ languages: [
+ {
+ language: "af",
+ percentage: 99,
+ },
+ ],
+ };
+ extension.sendMessage([af_string, expected]);
+ yield extension.awaitMessage("done");
+
+ win.close();
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html b/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html
new file mode 100644
index 000000000..7c6a8eeaa
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html
@@ -0,0 +1,116 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_i18n_css() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background: function() {
+ function backgroundFetch(url) {
+ return new Promise((resolve, reject) => {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.onload = () => { resolve(xhr.responseText); };
+ xhr.onerror = reject;
+ xhr.send();
+ });
+ }
+
+ Promise.all([backgroundFetch("foo.css"), backgroundFetch("bar.CsS?x#y"), backgroundFetch("foo.txt")]).then(results => {
+ browser.test.assertEq("body { max-width: 42px; }", results[0], "CSS file localized");
+ browser.test.assertEq("body { max-width: 42px; }", results[1], "CSS file localized");
+
+ browser.test.assertEq("body { __MSG_foo__; }", results[2], "Text file not localized");
+
+ browser.test.notifyPass("i18n-css");
+ });
+
+ browser.test.sendMessage("ready", browser.runtime.getURL("foo.css"));
+ },
+
+ manifest: {
+ "web_accessible_resources": ["foo.css", "foo.txt", "locale.css"],
+
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "css": ["foo.css"],
+ }],
+
+ "default_locale": "en",
+ },
+
+ files: {
+ "_locales/en/messages.json": JSON.stringify({
+ "foo": {
+ "message": "max-width: 42px",
+ "description": "foo",
+ },
+ }),
+
+ "foo.css": "body { __MSG_foo__; }",
+ "bar.CsS": "body { __MSG_foo__; }",
+ "foo.txt": "body { __MSG_foo__; }",
+ "locale.css": '* { content: "__MSG_@@ui_locale__ __MSG_@@bidi_dir__ __MSG_@@bidi_reversed_dir__ __MSG_@@bidi_start_edge__ __MSG_@@bidi_end_edge__" }',
+ },
+ });
+
+ yield extension.startup();
+ let cssURL = yield extension.awaitMessage("ready");
+
+ function fetch(url) {
+ return new Promise((resolve, reject) => {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.onload = () => { resolve(xhr.responseText); };
+ xhr.onerror = reject;
+ xhr.send();
+ });
+ }
+
+ let css = yield fetch(cssURL);
+
+ is(css, "body { max-width: 42px; }", "CSS file localized in mochitest scope");
+
+ let win = window.open("file_sample.html");
+ yield waitForLoad(win);
+
+ let style = win.getComputedStyle(win.document.body);
+ is(style.maxWidth, "42px", "stylesheet correctly applied");
+ win.close();
+
+ cssURL = cssURL.replace(/foo.css$/, "locale.css");
+
+ css = yield fetch(cssURL);
+ is(css, '* { content: "en_US ltr rtl left right" }', "CSS file localized in mochitest scope");
+
+ const LOCALE = "general.useragent.locale";
+ const DIR = "intl.uidirection.en";
+
+ // We don't wind up actually switching the chrome registry locale, since we
+ // don't have a chrome package for Hebrew. So just override it.
+ SpecialPowers.setCharPref(LOCALE, "he");
+ SpecialPowers.setCharPref(DIR, "rtl");
+
+ css = yield fetch(cssURL);
+ is(css, '* { content: "he rtl ltr right left" }', "CSS file localized in mochitest scope");
+
+ SpecialPowers.clearUserPref(LOCALE);
+ SpecialPowers.clearUserPref(DIR);
+
+ yield extension.awaitFinish("i18n-css");
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html b/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html
new file mode 100644
index 000000000..675cbb298
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html
@@ -0,0 +1,49 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_in_incognito_context_true() {
+ function background() {
+ browser.runtime.onMessage.addListener(msg => {
+ browser.test.assertEq(true, msg, "inIncognitoContext is true");
+ browser.test.notifyPass("inIncognitoContext");
+ });
+
+ browser.windows.create({url: browser.runtime.getURL("/tab.html"), incognito: true});
+ }
+
+ function tabScript() {
+ browser.runtime.sendMessage(browser.extension.inIncognitoContext);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ files: {
+ "tab.js": tabScript,
+ "tab.html": `<!DOCTYPE html><html><head>
+ <meta charset="utf-8">
+ <script src="tab.js"><\/script>
+ </head></html>`,
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("inIncognitoContext");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html b/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html
new file mode 100644
index 000000000..da0c355e0
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html
@@ -0,0 +1,86 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <meta charset="utf-8">
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_versioned_js() {
+ // We need to deal with escaping the close script tags.
+ // May as well consolidate it into one place.
+ let script = attrs => `<script ${attrs}><\/script>`;
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "background": {"page": "background.html"},
+ },
+
+ files: {
+ "background.html": `
+ <meta charset="utf-8">
+ ${script('src="background.js" type="application/javascript"')}
+ ${script('src="background-1.js" type="application/javascript;version=1.8"')}
+ ${script('src="background-2.js" type="application/javascript;version=latest"')}
+ ${script('src="background-3.js" type="application/javascript"')}
+ `,
+
+ "background.js": function() {
+ window.reportResult = msg => {
+ browser.test.assertEq(
+ msg, "background-script-3",
+ "Expected a message only from the unversioned background script.");
+
+ browser.test.sendMessage("finished");
+ };
+ },
+
+ "background-1.js": function() {
+ window.reportResult("background-script-1");
+ },
+ "background-2.js": function() {
+ window.reportResult("background-script-2");
+ },
+ "background-3.js": function() {
+ window.reportResult("background-script-3");
+ },
+ },
+ });
+
+ let messages = [/Versioned JavaScript.*not supported in WebExtension.*developer\.mozilla\.org/,
+ /Versioned JavaScript.*not supported in WebExtension.*developer\.mozilla\.org/];
+
+ let waitForConsole = new Promise(resolve => {
+ SimpleTest.monitorConsole(resolve, messages);
+ });
+
+ info("loading extension");
+
+ yield Promise.all([extension.startup(),
+ extension.awaitMessage("finished")]);
+
+ info("waiting for console");
+
+ SimpleTest.endMonitorConsole();
+ yield waitForConsole;
+
+ info("unloading extension");
+
+ yield extension.unload();
+
+ info("test complete");
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html b/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html
new file mode 100644
index 000000000..ca8db873e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html
@@ -0,0 +1,63 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_listener_proxies() {
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "temporary",
+
+ manifest: {
+ "permissions": ["storage"],
+ },
+
+ async background() {
+ // Test that adding multiple listeners for the same event works as
+ // expected.
+
+ let awaitChanged = () => new Promise(resolve => {
+ browser.storage.onChanged.addListener(function listener() {
+ browser.storage.onChanged.removeListener(listener);
+ resolve();
+ });
+ });
+
+ let promises = [
+ awaitChanged(),
+ awaitChanged(),
+ ];
+
+ function removedListener() {}
+ browser.storage.onChanged.addListener(removedListener);
+ browser.storage.onChanged.removeListener(removedListener);
+
+ promises.push(awaitChanged(), awaitChanged());
+
+ browser.storage.local.set({foo: "bar"});
+
+ await Promise.all(promises);
+
+ browser.test.notifyPass("onchanged-listeners");
+ },
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("onchanged-listeners");
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html b/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html
new file mode 100644
index 000000000..d1b798cf9
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html
@@ -0,0 +1,224 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for notifications</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+// A 1x1 PNG image.
+// Source: https://commons.wikimedia.org/wiki/File:1x1.png (Public Domain)
+let image = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
+ "ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
+const IMAGE_ARRAYBUFFER = Uint8Array.from(image, byte => byte.charCodeAt(0)).buffer;
+
+add_task(function* test_notification() {
+ async function background() {
+ let opts = {
+ type: "basic",
+ title: "Testing Notification",
+ message: "Carry on",
+ };
+
+ let id = await browser.notifications.create(opts);
+
+ browser.test.sendMessage("running", id);
+ browser.test.notifyPass("background test passed");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ });
+ yield extension.startup();
+ let x = yield extension.awaitMessage("running");
+ is(x, "0", "got correct id from notifications.create");
+ yield extension.awaitFinish();
+ yield extension.unload();
+});
+
+add_task(function* test_notification_events() {
+ async function background() {
+ let opts = {
+ type: "basic",
+ title: "Testing Notification",
+ message: "Carry on",
+ };
+
+ // Test an ignored listener.
+ browser.notifications.onButtonClicked.addListener(function() {});
+
+ // We cannot test onClicked listener without a mock
+ // but we can attempt to add a listener.
+ browser.notifications.onClicked.addListener(function() {});
+
+ // Test onClosed listener.
+ browser.notifications.onClosed.addListener(id => {
+ browser.test.sendMessage("closed", id);
+ browser.test.notifyPass("background test passed");
+ });
+
+ await browser.notifications.create("5", opts);
+ let id = await browser.notifications.create("5", opts);
+ browser.test.sendMessage("running", id);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ });
+ yield extension.startup();
+ let x = yield extension.awaitMessage("closed");
+ is(x, "5", "got correct id from onClosed listener");
+ x = yield extension.awaitMessage("running");
+ is(x, "5", "got correct id from notifications.create");
+ yield extension.awaitFinish();
+ yield extension.unload();
+});
+
+add_task(function* test_notification_clear() {
+ async function background() {
+ let opts = {
+ type: "basic",
+ title: "Testing Notification",
+ message: "Carry on",
+ };
+
+ browser.notifications.onClosed.addListener(id => {
+ browser.test.sendMessage("closed", id);
+ });
+
+ let id = await browser.notifications.create("99", opts);
+
+ let wasCleared = await browser.notifications.clear(id);
+ browser.test.sendMessage("cleared", wasCleared);
+
+ browser.test.notifyPass("background test passed");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ });
+ yield extension.startup();
+ let x = yield extension.awaitMessage("closed");
+ is(x, "99", "got correct id from onClosed listener");
+ x = yield extension.awaitMessage("cleared");
+ is(x, true, "got correct boolean from notifications.clear");
+ yield extension.awaitFinish();
+ yield extension.unload();
+});
+
+add_task(function* test_notifications_empty_getAll() {
+ async function background() {
+ let notifications = await browser.notifications.getAll();
+
+ browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
+ browser.test.assertEq(0, Object.keys(notifications).length, "the object has no properties");
+ browser.test.notifyPass("getAll empty");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ });
+ yield extension.startup();
+ yield extension.awaitFinish("getAll empty");
+ yield extension.unload();
+});
+
+add_task(function* test_notifications_populated_getAll() {
+ async function background() {
+ let opts = {
+ type: "basic",
+ iconUrl: "a.png",
+ title: "Testing Notification",
+ message: "Carry on",
+ };
+
+ await browser.notifications.create("p1", opts);
+ await browser.notifications.create("p2", opts);
+ let notifications = await browser.notifications.getAll();
+
+ browser.test.assertEq("object", typeof notifications, "getAll() returned an object");
+ browser.test.assertEq(2, Object.keys(notifications).length, "the object has 2 properties");
+
+ for (let notificationId of ["p1", "p2"]) {
+ for (let key of Object.keys(opts)) {
+ browser.test.assertEq(
+ opts[key],
+ notifications[notificationId][key],
+ `the notification has the expected value for option: ${key}`
+ );
+ }
+ }
+
+ browser.test.notifyPass("getAll populated");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ files: {
+ "a.png": IMAGE_ARRAYBUFFER,
+ },
+ });
+ yield extension.startup();
+ yield extension.awaitFinish("getAll populated");
+ yield extension.unload();
+});
+
+add_task(function* test_buttons_unsupported() {
+ function background() {
+ let opts = {
+ type: "basic",
+ title: "Testing Notification",
+ message: "Carry on",
+ buttons: [{title: "Button title"}],
+ };
+
+ let exception = {};
+ try {
+ browser.notifications.create(opts);
+ } catch (e) {
+ exception = e;
+ }
+
+ browser.test.assertTrue(
+ String(exception).includes('Property "buttons" is unsupported by Firefox'),
+ "notifications.create with buttons option threw an expected exception"
+ );
+ browser.test.notifyPass("buttons-unsupported");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["notifications"],
+ },
+ background,
+ });
+ yield extension.startup();
+ yield extension.awaitFinish("buttons-unsupported");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html b/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html
new file mode 100644
index 000000000..07967d5d0
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html
@@ -0,0 +1,119 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension Test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* test_simple() {
+ async function runTests(cx) {
+ function xhr(XMLHttpRequest) {
+ return (url) => {
+ return new Promise((resolve, reject) => {
+ let req = new XMLHttpRequest();
+ req.open("GET", url);
+ req.addEventListener("load", resolve);
+ req.addEventListener("error", reject);
+ req.send();
+ });
+ };
+ }
+
+ function run(shouldFail, fetch) {
+ function passListener() {
+ browser.test.succeed(`${cx}.${fetch.name} pass listener`);
+ }
+
+ function failListener() {
+ browser.test.fail(`${cx}.${fetch.name} fail listener`);
+ }
+
+ /* eslint-disable no-else-return */
+ if (shouldFail) {
+ return fetch("http://example.org/example.txt").then(failListener, passListener);
+ } else {
+ return fetch("http://example.com/example.txt").then(passListener, failListener);
+ }
+ /* eslint-enable no-else-return */
+ }
+
+ try {
+ await run(true, xhr(XMLHttpRequest));
+ await run(false, xhr(XMLHttpRequest));
+ await run(true, xhr(window.XMLHttpRequest));
+ await run(false, xhr(window.XMLHttpRequest));
+ await run(true, fetch);
+ await run(false, fetch);
+ await run(true, window.fetch);
+ await run(false, window.fetch);
+ } catch (err) {
+ browser.test.fail(`Error: ${err} :: ${err.stack}`);
+ browser.test.notifyFail("permission_xhr");
+ }
+ }
+
+ async function background(runTestsFn) {
+ await runTestsFn("bg");
+ browser.test.notifyPass("permission_xhr");
+ }
+
+ let extensionData = {
+ background: `(${background})(${runTests})`,
+ manifest: {
+ permissions: ["http://example.com/"],
+ content_scripts: [{
+ "matches": ["http://mochi.test/*/file_permission_xhr.html"],
+ "js": ["content.js"],
+ }],
+ },
+ files: {
+ "content.js": `(${async runTestsFn => {
+ await runTestsFn("content");
+
+ window.wrappedJSObject.privilegedFetch = fetch;
+ window.wrappedJSObject.privilegedXHR = XMLHttpRequest;
+
+ window.addEventListener("message", function rcv({data}) {
+ switch (data.msg) {
+ case "test":
+ break;
+
+ case "assertTrue":
+ browser.test.assertTrue(data.condition, data.description);
+ break;
+
+ case "finish":
+ window.removeEventListener("message", rcv, false);
+ browser.test.sendMessage("content-script-finished");
+ break;
+ }
+ }, false);
+ window.postMessage("test", "*");
+ }})(${runTests})`,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_permission_xhr.html");
+ yield extension.awaitMessage("content-script-finished");
+ win.close();
+
+ yield extension.awaitFinish("permission_xhr");
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html
new file mode 100644
index 000000000..60351eaee
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html
@@ -0,0 +1,83 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.runtime.onConnect.addListener(port => {
+ browser.test.assertEq(port.name, "ernie", "port name correct");
+ browser.test.assertTrue(port.sender.url.endsWith("file_sample.html"), "URL correct");
+ browser.test.assertTrue(port.sender.tab.url.endsWith("file_sample.html"), "tab URL correct");
+
+ let expected = "message 1";
+ port.onMessage.addListener(msg => {
+ browser.test.assertEq(msg, expected, "message is expected");
+ if (expected == "message 1") {
+ port.postMessage("message 2");
+ expected = "message 3";
+ } else if (expected == "message 3") {
+ expected = "disconnect";
+ browser.test.notifyPass("runtime.connect");
+ }
+ });
+ port.onDisconnect.addListener(() => {
+ browser.test.assertEq(null, port.error, "No error because port is closed by disconnect() at other end");
+ browser.test.assertEq(expected, "disconnect", "got disconnection at right time");
+ });
+ });
+}
+
+function contentScript() {
+ let port = browser.runtime.connect({name: "ernie"});
+ port.postMessage("message 1");
+ port.onMessage.addListener(msg => {
+ if (msg == "message 2") {
+ port.postMessage("message 3");
+ port.disconnect();
+ }
+ });
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_start",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), extension.awaitFinish("runtime.connect")]);
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html
new file mode 100644
index 000000000..dce12b21b
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html
@@ -0,0 +1,103 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function backgroundScript(token) {
+ browser.runtime.onMessage.addListener(msg => {
+ browser.test.assertEq(msg, "done");
+ browser.test.notifyPass("sendmessage_reply");
+ });
+
+ browser.runtime.onConnect.addListener(port => {
+ browser.test.assertTrue(port.sender.url.endsWith("file_sample.html"), "sender url correct");
+ browser.test.assertTrue(port.sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ let tabId = port.sender.tab.id;
+ browser.tabs.connect(tabId, {name: token});
+
+ browser.test.assertEq(port.name, token, "token matches");
+ port.postMessage(token + "-done");
+ });
+
+ browser.test.sendMessage("background-ready");
+}
+
+function contentScript(token) {
+ let gotTabMessage = false;
+ let badTabMessage = false;
+ browser.runtime.onConnect.addListener(port => {
+ if (port.name == token) {
+ gotTabMessage = true;
+ } else {
+ badTabMessage = true;
+ }
+ port.disconnect();
+ });
+
+ let port = browser.runtime.connect(null, {name: token});
+ port.onMessage.addListener(function(msg) {
+ if (msg != token + "-done" || !gotTabMessage || badTabMessage) {
+ return; // test failed
+ }
+
+ // FIXME: Removing this line causes the test to fail:
+ // resource://gre/modules/ExtensionUtils.jsm, line 651: NS_ERROR_NOT_INITIALIZED
+ port.disconnect();
+ browser.runtime.sendMessage("done");
+ });
+}
+
+function makeExtension() {
+ let token = Math.random();
+ let extensionData = {
+ background: `(${backgroundScript})("${token}")`,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+ },
+
+ files: {
+ "content_script.js": `(${contentScript})("${token}")`,
+ },
+ };
+ return extensionData;
+}
+
+add_task(function* test_contentscript() {
+ let extension1 = ExtensionTestUtils.loadExtension(makeExtension());
+ let extension2 = ExtensionTestUtils.loadExtension(makeExtension());
+ yield Promise.all([extension1.startup(), extension2.startup()]);
+
+ yield extension1.awaitMessage("background-ready");
+ yield extension2.awaitMessage("background-ready");
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win),
+ extension1.awaitFinish("sendmessage_reply"),
+ extension2.awaitFinish("sendmessage_reply")]);
+
+ win.close();
+
+ yield extension1.unload();
+ yield extension2.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html
new file mode 100644
index 000000000..e84134eff
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html
@@ -0,0 +1,127 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+add_task(function* test_connect_bidirectionally_and_postMessage() {
+ function background() {
+ let onConnectCount = 0;
+ browser.runtime.onConnect.addListener(port => {
+ // 3. onConnect by connect() from CS.
+ browser.test.assertEq("from-cs", port.name);
+ browser.test.assertEq(1, ++onConnectCount,
+ "BG onConnect should be called once");
+
+ let tabId = port.sender.tab.id;
+ browser.test.assertTrue(tabId, "content script must have a tab ID");
+
+ let port2;
+ let postMessageCount1 = 0;
+ port.onMessage.addListener(msg => {
+ // 11. port.onMessage by port.postMessage in CS.
+ browser.test.assertEq("from CS to port", msg);
+ browser.test.assertEq(1, ++postMessageCount1,
+ "BG port.onMessage should be called once");
+
+ // 12. should trigger port2.onMessage in CS.
+ port2.postMessage("from BG to port2");
+ });
+
+ // 4. Should trigger onConnect in CS.
+ port2 = browser.tabs.connect(tabId, {name: "from-bg"});
+ let postMessageCount2 = 0;
+ port2.onMessage.addListener(msg => {
+ // 7. onMessage by port2.postMessage in CS.
+ browser.test.assertEq("from CS to port2", msg);
+ browser.test.assertEq(1, ++postMessageCount2,
+ "BG port2.onMessage should be called once");
+
+ // 8. Should trigger port.onMessage in CS.
+ port.postMessage("from BG to port");
+ });
+ });
+
+ // 1. Notify test runner to create a new tab.
+ browser.test.sendMessage("ready");
+ }
+
+ function contentScript() {
+ let onConnectCount = 0;
+ let port;
+ browser.runtime.onConnect.addListener(port2 => {
+ // 5. onConnect by connect() from BG.
+ browser.test.assertEq("from-bg", port2.name);
+ browser.test.assertEq(1, ++onConnectCount,
+ "CS onConnect should be called once");
+
+ let postMessageCount2 = 0;
+ port2.onMessage.addListener(msg => {
+ // 12. port2.onMessage by port2.postMessage in BG.
+ browser.test.assertEq("from BG to port2", msg);
+ browser.test.assertEq(1, ++postMessageCount2,
+ "CS port2.onMessage should be called once");
+
+ // TODO(robwu): Do not explicitly disconnect, it should not be a problem
+ // if we keep the ports open. However, not closing the ports causes the
+ // test to fail with NS_ERROR_NOT_INITIALIZED in ExtensionUtils.jsm, in
+ // Port.prototype.disconnect (nsIMessageSender.sendAsyncMessage).
+ port.disconnect();
+ port2.disconnect();
+ browser.test.notifyPass("ping pong done");
+ });
+ // 6. should trigger port2.onMessage in BG.
+ port2.postMessage("from CS to port2");
+ });
+
+ // 2. should trigger onConnect in BG.
+ port = browser.runtime.connect({name: "from-cs"});
+ let postMessageCount1 = 0;
+ port.onMessage.addListener(msg => {
+ // 9. onMessage by port.postMessage in BG.
+ browser.test.assertEq("from BG to port", msg);
+ browser.test.assertEq(1, ++postMessageCount1,
+ "CS port.onMessage should be called once");
+
+ // 10. should trigger port.onMessage in BG.
+ port.postMessage("from CS to port");
+ });
+ }
+
+ let extensionData = {
+ background,
+ manifest: {
+ content_scripts: [{
+ js: ["contentscript.js"],
+ matches: ["http://mochi.test/*/file_sample.html"],
+ }],
+ },
+ files: {
+ "contentscript.js": contentScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ info("extension loaded");
+
+ yield extension.awaitMessage("ready");
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitFinish("ping pong done");
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+</body>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html
new file mode 100644
index 000000000..5764d0a3c
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html
@@ -0,0 +1,78 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.runtime.onConnect.addListener(port => {
+ browser.test.assertEq(port.name, "ernie", "port name correct");
+ port.onDisconnect.addListener(() => {
+ browser.test.assertEq(null, port.error, "The port is implicitly closed without errors when the other context unloads");
+ // Closing an already-disconnected port is a no-op.
+ port.disconnect();
+ port.disconnect();
+ browser.test.sendMessage("disconnected");
+ });
+ browser.test.sendMessage("connected");
+ });
+}
+
+function contentScript() {
+ browser.runtime.connect({name: "ernie"});
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield Promise.all([waitForLoad(win), extension.awaitMessage("connected")]);
+ win.close();
+ yield extension.awaitMessage("disconnected");
+
+ info("win.close() succeeded");
+
+ win = window.open("file_sample.html");
+ yield Promise.all([waitForLoad(win), extension.awaitMessage("connected")]);
+
+ // Add an "unload" listener so that we don't put the window in the
+ // bfcache. This way it gets destroyed immediately upon navigation.
+ win.addEventListener("unload", function() {}); // eslint-disable-line mozilla/balanced-listeners
+
+ win.location = "http://example.com";
+ yield extension.awaitMessage("disconnected");
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html
new file mode 100644
index 000000000..4cdefda41
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html
@@ -0,0 +1,61 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <meta charset="utf-8">
+ <title>Test for browser.runtime.id</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_runtime_id() {
+ function background() {
+ browser.test.sendMessage("background-id", browser.runtime.id);
+ }
+
+ function content() {
+ browser.test.sendMessage("content-id", browser.runtime.id);
+ }
+
+ let uuidGenerator = SpecialPowers.Cc["@mozilla.org/uuid-generator;1"].getService(SpecialPowers.Ci.nsIUUIDGenerator);
+ let id = uuidGenerator.generateUUID().number;
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ applications: {gecko: {id}},
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "run_at": "document_start",
+ "js": ["content_script.js"],
+ }],
+ },
+
+ background,
+
+ files: {
+ "content_script.js": content,
+ },
+ });
+
+ yield extension.startup();
+
+ let backgroundId = yield extension.awaitMessage("background-id");
+ is(backgroundId, id, "runtime.id from background script is correct");
+ let win = window.open("file_sample.html");
+ let contentId = yield extension.awaitMessage("content-id");
+ is(contentId, id, "runtime.id from content script is correct");
+
+ win.close();
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html b/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html
new file mode 100644
index 000000000..426a71ac6
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html
@@ -0,0 +1,60 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.runtime.onMessage.addListener(result => {
+ browser.test.assertEq(result, 12, "x is 12");
+ browser.test.notifyPass("background test passed");
+ });
+}
+
+function contentScript() {
+ window.x = 12;
+ browser.runtime.onMessage.addListener(function() {});
+ browser.runtime.sendMessage(window.x);
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), extension.awaitFinish()]);
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_schema.html b/toolkit/components/webextensions/test/mochitest/test_ext_schema.html
new file mode 100644
index 000000000..8a0e11c56
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_schema.html
@@ -0,0 +1,73 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for schema API creation</title>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="chrome_head.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* testEmptySchema() {
+ function background() {
+ browser.test.assertEq(undefined, browser.manifest, "browser.manifest is not defined");
+ browser.test.assertTrue("storage" in browser, "browser.storage should be defined");
+ browser.test.assertEq(undefined, browser.contextMenus, "browser.contextMenus should not be defined");
+ browser.test.notifyPass("schema");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["storage"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("schema");
+ yield extension.unload();
+});
+
+add_task(function* testUnknownProperties() {
+ function background() {
+ browser.test.notifyPass("loaded");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["unknownPermission"],
+
+ unknown_property: {},
+ },
+
+ background,
+ });
+
+ let messages = [
+ {message: /processing permissions\.0: Unknown permission "unknownPermission"/},
+ {message: /processing unknown_property: An unexpected property was found in the WebExtension manifest/},
+ ];
+
+ let waitForConsole = new Promise(resolve => {
+ SimpleTest.monitorConsole(resolve, messages);
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("loaded");
+
+ yield extension.unload();
+
+ SimpleTest.endMonitorConsole();
+ yield waitForConsole;
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html
new file mode 100644
index 000000000..a3ef37cad
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html
@@ -0,0 +1,101 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ // Add two listeners that both send replies. We're supposed to ignore all but one
+ // of them. Which one is chosen is non-deterministic.
+
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ browser.test.assertTrue(sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ if (msg == "getreply") {
+ sendReply("reply1");
+ }
+ });
+
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ browser.test.assertTrue(sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ if (msg == "getreply") {
+ sendReply("reply2");
+ }
+ });
+
+ function sleep(callback, n = 10) {
+ if (n == 0) {
+ callback();
+ } else {
+ setTimeout(function() { sleep(callback, n - 1); }, 0);
+ }
+ }
+
+ let done_count = 0;
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ browser.test.assertTrue(sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ if (msg == "done") {
+ done_count++;
+ browser.test.assertEq(done_count, 1, "got exactly one reply");
+
+ // Go through the event loop a few times to make sure we don't get multiple replies.
+ sleep(function() {
+ browser.test.notifyPass("sendmessage_doublereply");
+ });
+ }
+ });
+}
+
+function contentScript() {
+ browser.runtime.sendMessage("getreply", function(resp) {
+ if (resp != "reply1" && resp != "reply2") {
+ return; // test failed
+ }
+ browser.runtime.sendMessage("done");
+ });
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_start",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), extension.awaitFinish("sendmessage_doublereply")]);
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html
new file mode 100644
index 000000000..96af6558e
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html
@@ -0,0 +1,83 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <meta charset="utf-8">
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+<script>
+"use strict";
+
+function loadContentScriptExtension(contentScript) {
+ let extensionData = {
+ manifest: {
+ "content_scripts": [{
+ "js": ["contentscript.js"],
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ }],
+ },
+ files: {
+ "contentscript.js": contentScript,
+ },
+ };
+ return ExtensionTestUtils.loadExtension(extensionData);
+}
+
+add_task(function* test_content_script_sendMessage_without_listener() {
+ async function contentScript() {
+ await browser.test.assertRejects(
+ browser.runtime.sendMessage("msg"),
+ "Could not establish connection. Receiving end does not exist.");
+
+ browser.test.notifyPass("sendMessage callback was invoked");
+ }
+
+ let extension = loadContentScriptExtension(contentScript);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitFinish("sendMessage callback was invoked");
+ win.close();
+
+ yield extension.unload();
+});
+
+add_task(function* test_content_script_chrome_sendMessage_without_listener() {
+ function contentScript() {
+ /* globals chrome */
+ browser.test.assertEq(null, chrome.runtime.lastError, "no lastError before call");
+ let retval = chrome.runtime.sendMessage("msg");
+ browser.test.assertEq(null, chrome.runtime.lastError, "no lastError after call");
+ // TODO(robwu): Fix the implementation and uncomment the next expectation.
+ // When content script APIs are schema-based (bugzil.la/1287007) this bug will be fixed for free.
+ // browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage without callback");
+ browser.test.assertTrue(retval instanceof Promise, "TODO: chrome.runtime.sendMessage should return undefined, not a promise");
+
+ let isAsyncCall = false;
+ retval = chrome.runtime.sendMessage("msg", reply => {
+ browser.test.assertEq(undefined, reply, "no reply");
+ browser.test.assertTrue(isAsyncCall, "chrome.runtime.sendMessage's callback must be called asynchronously");
+ browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage with callback");
+ browser.test.assertEq("Could not establish connection. Receiving end does not exist.", chrome.runtime.lastError.message);
+ browser.test.notifyPass("finished chrome.runtime.sendMessage");
+ });
+ isAsyncCall = true;
+ }
+
+ let extension = loadContentScriptExtension(contentScript);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+ yield extension.awaitFinish("finished chrome.runtime.sendMessage");
+ win.close();
+
+ yield extension.unload();
+});
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html
new file mode 100644
index 000000000..a4ac708b2
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html
@@ -0,0 +1,79 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function background() {
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ browser.test.assertTrue(sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ if (msg == 0) {
+ sendReply("reply1");
+ } else if (msg == 1) {
+ window.setTimeout(function() {
+ sendReply("reply2");
+ }, 0);
+ return true;
+ } else if (msg == 2) {
+ browser.test.notifyPass("sendmessage_reply");
+ }
+ });
+}
+
+function contentScript() {
+ browser.runtime.sendMessage(0, function(resp1) {
+ if (resp1 != "reply1") {
+ return; // test failed
+ }
+ browser.runtime.sendMessage(1, function(resp2) {
+ if (resp2 != "reply2") {
+ return; // test failed
+ }
+ browser.runtime.sendMessage(2);
+ });
+ });
+}
+
+let extensionData = {
+ background,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+ },
+
+ files: {
+ "content_script.js": contentScript,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win), extension.awaitFinish("sendmessage_reply")]);
+
+ win.close();
+
+ yield extension.unload();
+ info("extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html
new file mode 100644
index 000000000..1ebc1b40f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html
@@ -0,0 +1,93 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+function backgroundScript(token) {
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ browser.test.assertTrue(sender.tab.url.endsWith("file_sample.html"), "sender url correct");
+
+ if (msg == "done") {
+ browser.test.notifyPass("sendmessage_reply");
+ return;
+ }
+
+ let tabId = sender.tab.id;
+ browser.tabs.sendMessage(tabId, `${token}-tabMessage`);
+
+ browser.test.assertEq(msg, token, "token matches");
+ sendReply(`${token}-done`);
+ });
+}
+
+function contentScript(token) {
+ let gotTabMessage = false;
+ let badTabMessage = false;
+ browser.runtime.onMessage.addListener((msg, sender, sendReply) => {
+ if (msg == `${token}-tabMessage`) {
+ gotTabMessage = true;
+ } else {
+ badTabMessage = true;
+ }
+ });
+
+ browser.runtime.sendMessage(token, function(resp) {
+ if (resp != `${token}-done` || !gotTabMessage || badTabMessage) {
+ return; // test failed
+ }
+ browser.runtime.sendMessage("done");
+ });
+}
+
+function makeExtension() {
+ let token = Math.random();
+ let extensionData = {
+ background: `(${backgroundScript})(${token})`,
+ manifest: {
+ "permissions": ["tabs"],
+ "content_scripts": [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_start",
+ }],
+ },
+
+ files: {
+ "content_script.js": `(${contentScript})(${token})`,
+ },
+ };
+ return extensionData;
+}
+
+add_task(function* test_contentscript() {
+ let extension1 = ExtensionTestUtils.loadExtension(makeExtension());
+ let extension2 = ExtensionTestUtils.loadExtension(makeExtension());
+
+ yield Promise.all([extension1.startup(), extension2.startup()]);
+
+ let win = window.open("file_sample.html");
+
+ yield Promise.all([waitForLoad(win),
+ extension1.awaitFinish("sendmessage_reply"),
+ extension2.awaitFinish("sendmessage_reply")]);
+
+ win.close();
+
+ yield extension1.unload();
+ yield extension2.unload();
+ info("extensions unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html b/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html
new file mode 100644
index 000000000..09a33814a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html
@@ -0,0 +1,330 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="application/javascript">
+"use strict";
+
+// Copied from toolkit/components/extensions/test/xpcshell/test_ext_storage.js.
+// The storage API in content scripts should behave identical to the storage API
+// in background pages.
+const STORAGE_SYNC_PREF = "webextensions.storage.sync.enabled";
+/**
+ * Utility function to ensure that all supported APIs for getting are
+ * tested.
+ *
+ * @param {string} areaName
+ * either "local" or "sync" according to what we want to test
+ * @param {string} prop
+ * "key" to look up using the storage API
+ * @param {Object} value
+ * "value" to compare against
+ */
+async function checkGetImpl(areaName, prop, value) {
+ let storage = browser.storage[areaName];
+
+ let data = await storage.get(null);
+ browser.test.assertEq(value, data[prop], `null getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get(prop);
+ browser.test.assertEq(value, data[prop], `string getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get([prop]);
+ browser.test.assertEq(value, data[prop], `array getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get({[prop]: undefined});
+ browser.test.assertEq(value, data[prop], `object getter worked for ${prop} in ${areaName}`);
+}
+
+async function contentScript(checkGet) {
+ let globalChanges, gResolve;
+ function clearGlobalChanges() {
+ globalChanges = new Promise(resolve => { gResolve = resolve; });
+ }
+ clearGlobalChanges();
+ let expectedAreaName;
+
+ browser.storage.onChanged.addListener((changes, areaName) => {
+ browser.test.assertEq(expectedAreaName, areaName,
+ "Expected area name received by listener");
+ gResolve(changes);
+ });
+
+ async function checkChanges(areaName, changes, message) {
+ function checkSub(obj1, obj2) {
+ for (let prop in obj1) {
+ browser.test.assertTrue(obj1[prop] !== undefined,
+ `checkChanges ${areaName} ${prop} is missing (${message})`);
+ browser.test.assertTrue(obj2[prop] !== undefined,
+ `checkChanges ${areaName} ${prop} is missing (${message})`);
+ browser.test.assertEq(obj1[prop].oldValue, obj2[prop].oldValue,
+ `checkChanges ${areaName} ${prop} old (${message})`);
+ browser.test.assertEq(obj1[prop].newValue, obj2[prop].newValue,
+ `checkChanges ${areaName} ${prop} new (${message})`);
+ }
+ }
+
+ const recentChanges = await globalChanges;
+ checkSub(changes, recentChanges);
+ checkSub(recentChanges, changes);
+ clearGlobalChanges();
+ }
+
+ /* eslint-disable dot-notation */
+ async function runTests(areaName) {
+ expectedAreaName = areaName;
+ let storage = browser.storage[areaName];
+ // Set some data and then test getters.
+ try {
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+ await checkChanges(areaName,
+ {"test-prop1": {newValue: "value1"}, "test-prop2": {newValue: "value2"}},
+ "set (a)");
+
+ await checkGet(areaName, "test-prop1", "value1");
+ await checkGet(areaName, "test-prop2", "value2");
+
+ let data = await storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
+ browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (a)");
+ browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (a)");
+ browser.test.assertEq("default", data["other"], "other correct");
+
+ data = await storage.get(["test-prop1", "test-prop2", "other"]);
+ browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (b)");
+ browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (b)");
+ browser.test.assertFalse("other" in data, "other correct");
+
+ // Remove data in various ways.
+ await storage.remove("test-prop1");
+ await checkChanges(areaName, {"test-prop1": {oldValue: "value1"}}, "remove string");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove string)");
+ browser.test.assertTrue("test-prop2" in data, "prop2 present (remove string)");
+
+ await storage.set({"test-prop1": "value1"});
+ await checkChanges(areaName, {"test-prop1": {newValue: "value1"}}, "set (c)");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertEq(data["test-prop1"], "value1", "prop1 correct (c)");
+ browser.test.assertEq(data["test-prop2"], "value2", "prop2 correct (c)");
+
+ await storage.remove(["test-prop1", "test-prop2"]);
+ await checkChanges(areaName,
+ {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}},
+ "remove array");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove array)");
+ browser.test.assertFalse("test-prop2" in data, "prop2 absent (remove array)");
+
+ // test storage.clear
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+ // Make sure that set() handler happened before we clear the
+ // promise again.
+ await globalChanges;
+
+ clearGlobalChanges();
+ await storage.clear();
+
+ await checkChanges(areaName,
+ {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}},
+ "clear");
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (clear)");
+ browser.test.assertFalse("test-prop2" in data, "prop2 absent (clear)");
+
+ // Make sure we can store complex JSON data.
+ // known previous values
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+
+ // Make sure the set() handler landed.
+ await globalChanges;
+
+ clearGlobalChanges();
+ await storage.set({
+ "test-prop1": {
+ str: "hello",
+ bool: true,
+ null: null,
+ undef: undefined,
+ obj: {},
+ arr: [1, 2],
+ date: new Date(0),
+ regexp: /regexp/,
+ func: function func() {},
+ window,
+ },
+ });
+
+ await storage.set({"test-prop2": function func() {}});
+ const recentChanges = await globalChanges;
+
+ browser.test.assertEq("value1", recentChanges["test-prop1"].oldValue, "oldValue correct");
+ browser.test.assertEq("object", typeof(recentChanges["test-prop1"].newValue), "newValue is obj");
+ clearGlobalChanges();
+
+ data = await storage.get({"test-prop1": undefined, "test-prop2": undefined});
+ let obj = data["test-prop1"];
+
+ browser.test.assertEq("hello", obj.str, "string part correct");
+ browser.test.assertEq(true, obj.bool, "bool part correct");
+ browser.test.assertEq(null, obj.null, "null part correct");
+ browser.test.assertEq(undefined, obj.undef, "undefined part correct");
+ browser.test.assertEq(undefined, obj.func, "function part correct");
+ browser.test.assertEq(undefined, obj.window, "window part correct");
+ browser.test.assertEq("1970-01-01T00:00:00.000Z", obj.date, "date part correct");
+ browser.test.assertEq("/regexp/", obj.regexp, "regexp part correct");
+ browser.test.assertEq("object", typeof(obj.obj), "object part correct");
+ browser.test.assertTrue(Array.isArray(obj.arr), "array part present");
+ browser.test.assertEq(1, obj.arr[0], "arr[0] part correct");
+ browser.test.assertEq(2, obj.arr[1], "arr[1] part correct");
+ browser.test.assertEq(2, obj.arr.length, "arr.length part correct");
+
+ obj = data["test-prop2"];
+
+ browser.test.assertEq("[object Object]", {}.toString.call(obj), "function serialized as a plain object");
+ browser.test.assertEq(0, Object.keys(obj).length, "function serialized as an empty object");
+ } catch (e) {
+ browser.test.fail(`Error: ${e} :: ${e.stack}`);
+ browser.test.notifyFail("storage");
+ }
+ }
+
+ browser.test.onMessage.addListener(msg => {
+ let promise;
+ if (msg === "test-local") {
+ promise = runTests("local");
+ } else if (msg === "test-sync") {
+ promise = runTests("sync");
+ }
+ promise.then(() => browser.test.sendMessage("test-finished"));
+ });
+
+ browser.test.sendMessage("ready");
+}
+
+let extensionData = {
+ manifest: {
+ content_scripts: [{
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ }],
+
+ permissions: ["storage"],
+ },
+
+ files: {
+ "content_script.js": `(${contentScript})(${checkGetImpl})`,
+ },
+};
+
+add_task(function* test_contentscript() {
+ let win = window.open("file_sample.html");
+ yield waitForLoad(win);
+
+ yield SpecialPowers.pushPrefEnv({
+ set: [[STORAGE_SYNC_PREF, true]],
+ });
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
+ extension.sendMessage("test-local");
+ yield extension.awaitMessage("test-finished");
+
+ extension.sendMessage("test-sync");
+ yield extension.awaitMessage("test-finished");
+
+ yield SpecialPowers.popPrefEnv();
+ yield extension.unload();
+
+ win.close();
+});
+
+add_task(function* test_local_cache_invalidation() {
+ let win = window.open("file_sample.html");
+
+ function background(checkGet) {
+ browser.test.onMessage.addListener(async msg => {
+ if (msg === "set-initial") {
+ await browser.storage.local.set({"test-prop1": "value1", "test-prop2": "value2"});
+ browser.test.sendMessage("set-initial-done");
+ } else if (msg === "check") {
+ await checkGet("local", "test-prop1", "value1");
+ await checkGet("local", "test-prop2", "value2");
+ browser.test.sendMessage("check-done");
+ }
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["storage"],
+ },
+ background: `(${background})(${checkGetImpl})`,
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage("set-initial");
+ yield extension.awaitMessage("set-initial-done");
+
+ SpecialPowers.invalidateExtensionStorageCache();
+
+ extension.sendMessage("check");
+ yield extension.awaitMessage("check-done");
+
+ yield extension.unload();
+ win.close();
+});
+
+add_task(function* test_config_flag_needed() {
+ let win = window.open("file_sample.html");
+ yield waitForLoad(win);
+
+ function background() {
+ let promises = [];
+ let apiTests = [
+ {method: "get", args: ["foo"]},
+ {method: "set", args: [{foo: "bar"}]},
+ {method: "remove", args: ["foo"]},
+ {method: "clear", args: []},
+ ];
+ apiTests.forEach(testDef => {
+ promises.push(browser.test.assertRejects(
+ browser.storage.sync[testDef.method](...testDef.args),
+ "Please set webextensions.storage.sync.enabled to true in about:config",
+ `storage.sync.${testDef.method} is behind a flag`));
+ });
+
+ Promise.all(promises).then(() => browser.test.notifyPass("flag needed"));
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["storage"],
+ },
+ background: `(${background})(${checkGetImpl})`,
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("flag needed");
+ yield extension.unload();
+ win.close();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html b/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html
new file mode 100644
index 000000000..32d8e6af0
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html
@@ -0,0 +1,118 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_multiple_pages() {
+ async function background() {
+ let tabReady = new Promise(resolve => {
+ browser.runtime.onMessage.addListener(function listener(msg) {
+ browser.test.log("onMessage " + msg);
+ if (msg == "tab-ready") {
+ browser.runtime.onMessage.removeListener(listener);
+ resolve();
+ }
+ });
+ });
+
+ let tabId;
+ let tabRemoved = new Promise(resolve => {
+ browser.tabs.onRemoved.addListener(function listener(removedId) {
+ if (removedId == tabId) {
+ browser.tabs.onRemoved.removeListener(listener);
+
+ // Delay long enough to be sure the inner window has been nuked.
+ setTimeout(resolve, 0);
+ }
+ });
+ });
+
+ try {
+ let storage = browser.storage.local;
+
+ browser.test.log("create");
+ let tab = await browser.tabs.create({url: "tab.html"});
+ tabId = tab.id;
+
+ await tabReady;
+
+ let result = await storage.get("key");
+ browser.test.assertEq(undefined, result.key, "Key should be undefined");
+
+ await browser.runtime.sendMessage("tab-set-key");
+
+ result = await storage.get("key");
+ browser.test.assertEq(JSON.stringify({foo: {bar: "baz"}}),
+ JSON.stringify(result.key),
+ "Key should be set to the value from the tab");
+
+ browser.test.log("Remove tab");
+
+ await Promise.all([
+ browser.tabs.remove(tabId),
+ tabRemoved,
+ ]);
+
+ result = await storage.get("key");
+ browser.test.assertEq(JSON.stringify({foo: {bar: "baz"}}),
+ JSON.stringify(result.key),
+ "Key should still be set to the value from the tab");
+
+ browser.test.notifyPass("storage-multiple");
+ } catch (e) {
+ browser.test.fail(`Error: ${e} :: ${e.stack}`);
+ browser.test.notifyFail("storage-multiple");
+ }
+ }
+
+ function tab() {
+ browser.test.log("tab");
+ browser.runtime.onMessage.addListener(msg => {
+ if (msg == "tab-set-key") {
+ return browser.storage.local.set({key: {foo: {bar: "baz"}}});
+ }
+ });
+
+ browser.runtime.sendMessage("tab-ready");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+
+ files: {
+ "tab.html": `<!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <script src="tab.js"><\/script>
+ </head>
+ </html>`,
+
+ "tab.js": tab,
+ },
+
+ manifest: {
+ permissions: ["storage"],
+ },
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("storage-multiple");
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html b/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html
new file mode 100644
index 000000000..1f3a9a3c9
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html
@@ -0,0 +1,202 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtension test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_webext_tab_subframe_privileges() {
+ function background() {
+ browser.runtime.onMessage.addListener(async ({msg, success, tabId, error}) => {
+ if (msg == "webext-tab-subframe-privileges") {
+ if (success) {
+ await browser.tabs.remove(tabId);
+
+ browser.test.notifyPass(msg);
+ } else {
+ browser.test.log(`Got an unexpected error: ${error}`);
+
+ let tabs = await browser.tabs.query({active: true});
+ await browser.tabs.remove(tabs[0].id);
+
+ browser.test.notifyFail(msg);
+ }
+ }
+ });
+ browser.tabs.create({url: browser.runtime.getURL("/tab.html")});
+ }
+
+ async function tabSubframeScript() {
+ browser.test.assertTrue(browser.tabs != undefined,
+ "Subframe of a privileged page has access to privileged APIs");
+ if (browser.tabs) {
+ try {
+ let tab = await browser.tabs.getCurrent();
+ browser.runtime.sendMessage({
+ msg: "webext-tab-subframe-privileges",
+ success: true,
+ tabId: tab.id,
+ });
+ } catch (e) {
+ browser.runtime.sendMessage({msg: "webext-tab-subframe-privileges", success: false, error: `${e}`});
+ }
+ } else {
+ browser.runtime.sendMessage({
+ msg: "webext-tab-subframe-privileges",
+ success: false,
+ error: `Privileged APIs missing in WebExtension tab sub-frame`,
+ });
+ }
+ }
+
+ let extensionData = {
+ background,
+ files: {
+ "tab.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ <body>
+ <iframe src="tab-subframe.html"></iframe>
+ </body>
+ </html>`,
+ "tab-subframe.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ <script src="tab-subframe.js"><\/script>
+ </head>
+ </html>`,
+ "tab-subframe.js": tabSubframeScript,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("webext-tab-subframe-privileges");
+ yield extension.unload();
+});
+
+add_task(function* test_webext_background_subframe_privileges() {
+ function backgroundSubframeScript() {
+ browser.test.assertTrue(browser.tabs != undefined,
+ "Subframe of a background page has access to privileged APIs");
+ browser.test.notifyPass("webext-background-subframe-privileges");
+ }
+
+ let extensionData = {
+ manifest: {
+ background: {
+ page: "background.html",
+ },
+ },
+ files: {
+ "background.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ <body>
+ <iframe src="background-subframe.html"></iframe>
+ </body>
+ </html>`,
+ "background-subframe.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ <script src="background-subframe.js"><\/script>
+ </head>
+ </html>`,
+ "background-subframe.js": backgroundSubframeScript,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("webext-background-subframe-privileges");
+ yield extension.unload();
+});
+
+add_task(function* test_webext_contentscript_iframe_subframe_privileges() {
+ function background() {
+ browser.runtime.onMessage.addListener(({name, hasTabsAPI, hasStorageAPI}) => {
+ if (name == "contentscript-iframe-loaded") {
+ browser.test.assertFalse(hasTabsAPI,
+ "Subframe of a content script privileged iframes has no access to privileged APIs");
+ browser.test.assertTrue(hasStorageAPI,
+ "Subframe of a content script privileged iframes has access to content script APIs");
+
+ browser.test.notifyPass("webext-contentscript-subframe-privileges");
+ }
+ });
+ }
+
+ function subframeScript() {
+ browser.runtime.sendMessage({
+ name: "contentscript-iframe-loaded",
+ hasTabsAPI: browser.tabs != undefined,
+ hasStorageAPI: browser.storage != undefined,
+ });
+ }
+
+ function contentScript() {
+ let iframe = document.createElement("iframe");
+ iframe.setAttribute("src", browser.runtime.getURL("/contentscript-iframe.html"));
+ document.body.appendChild(iframe);
+ }
+
+ let extensionData = {
+ background,
+ manifest: {
+ "permissions": ["storage"],
+ "content_scripts": [{
+ "matches": ["http://example.com/*"],
+ "js": ["contentscript.js"],
+ }],
+ web_accessible_resources: [
+ "contentscript-iframe.html",
+ ],
+ },
+ files: {
+ "contentscript.js": contentScript,
+ "contentscript-iframe.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ <body>
+ <iframe src="contentscript-iframe-subframe.html"></iframe>
+ </body>
+ </html>`,
+ "contentscript-iframe-subframe.html": `<!DOCTYPE>
+ <head>
+ <meta charset="utf-8">
+ <script src="contentscript-iframe-subframe.js"><\/script>
+ </head>
+ </html>`,
+ "contentscript-iframe-subframe.js": subframeScript,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ let win = window.open("http://example.com");
+
+ yield extension.awaitFinish("webext-contentscript-subframe-privileges");
+
+ win.close();
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html
new file mode 100644
index 000000000..dc351e48a
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html
@@ -0,0 +1,150 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for extension tab teardown</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+// Test for tabs opened using tabs.create and window.open
+function* runTabReloadAndCloseTest(extension) {
+ let chromeScript = SpecialPowers.loadChromeScript(
+ SimpleTest.getTestFileURL("file_teardown_test.js"));
+ yield chromeScript.promiseOneMessage("chromescript-startup");
+ function* getContextEvents() {
+ chromeScript.sendAsyncMessage("get-context-events");
+ let contextEvents = yield chromeScript.promiseOneMessage("context-events");
+ dump(JSON.stringify(contextEvents));
+ return contextEvents.filter(event => event.extensionId == extension.id);
+ }
+
+ extension.sendMessage("open extension page");
+ let extensionPageUrl = yield extension.awaitMessage("extension page loaded");
+
+ let contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1, "ExtensionContext change for opening a tab");
+ is(contextEvents[0].eventType, "load", "create ExtensionContext for tab");
+ is(contextEvents[0].url, extensionPageUrl,
+ "ExtensionContext URL after tab creation should be tab URL");
+
+ extension.sendMessage("reload extension page");
+ let extensionPageUrl2 = yield extension.awaitMessage("extension page loaded");
+
+ is(extensionPageUrl, extensionPageUrl2,
+ "The tab's URL is expected to not change after a page reload");
+
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 2, "ExtensionContext change after tab reload");
+ is(contextEvents[0].eventType, "unload", "unload old ExtensionContext");
+ is(contextEvents[0].url, extensionPageUrl,
+ "ExtensionContext URL before reload should be tab URL");
+ is(contextEvents[1].eventType, "load", "create new ExtensionContext for tab");
+ is(contextEvents[1].url, extensionPageUrl2,
+ "ExtensionContext URL after reload should be tab URL");
+
+ extension.sendMessage("close extension page");
+ yield extension.awaitMessage("closed extension page");
+
+ contextEvents = yield* getContextEvents();
+ is(contextEvents.length, 1, "ExtensionContext after closing tab");
+ is(contextEvents[0].eventType, "unload", "unload tab's ExtensionContext");
+ is(contextEvents[0].url, extensionPageUrl2,
+ "ExtensionContext URL at closing tab should be tab URL");
+
+ chromeScript.sendAsyncMessage("cleanup");
+ chromeScript.destroy();
+ yield extension.unload();
+}
+
+add_task(function* test_extension_page_tabs_create_reload_and_close() {
+ function background() {
+ let tabId;
+ browser.test.onMessage.addListener(msg => {
+ if (msg === "open extension page") {
+ chrome.tabs.create({url: "page.html"}, tab => {
+ tabId = tab.id;
+ });
+ } else if (msg === "reload extension page") {
+ chrome.tabs.reload(tabId);
+ } else if (msg === "close extension page") {
+ chrome.tabs.remove(tabId, () => {
+ browser.test.sendMessage("closed extension page");
+ });
+ }
+ });
+ }
+
+ function pageScript() {
+ browser.test.sendMessage("extension page loaded", document.URL);
+ }
+
+ let extensionData = {
+ background,
+ files: {
+ "page.html": `<!DOCTYPE html><meta charset="utf-8"><script src="page.js"><\/script>`,
+ "page.js": pageScript,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield* runTabReloadAndCloseTest(extension);
+});
+
+add_task(function* test_extension_page_window_open_reload_and_close() {
+ // This tests whether a context that is opened via window.open is properly
+ // disposed when the tab closes.
+ // The background page cannot use window.open (bugzil.la/1282021), so we open
+ // another extension page that manages the window.open-tab for testing.
+ function background() {
+ chrome.tabs.create({url: "window.open.html"});
+ }
+
+ function windowOpenScript() {
+ let win;
+ browser.test.onMessage.addListener(msg => {
+ if (msg === "open extension page") {
+ win = window.open("page.html");
+ } else if (msg === "reload extension page") {
+ win.location.reload();
+ } else if (msg === "close extension page") {
+ browser.tabs.onRemoved.addListener(function listener() {
+ browser.tabs.onRemoved.removeListener(listener);
+ browser.test.sendMessage("closed extension page");
+ });
+ win.close();
+ }
+ });
+ browser.test.sendMessage("setup-intermediate-tab");
+ }
+
+ function pageScript() {
+ browser.test.sendMessage("extension page loaded", document.URL);
+ }
+
+ let extensionData = {
+ background,
+ files: {
+ "page.html": `<!DOCTYPE html><meta charset="utf-8"><script src="page.js"><\/script>`,
+ "page.js": pageScript,
+ "window.open.html": `<!DOCTYPE html><meta charset="utf-8"><script src="window.open.js"><\/script>`,
+ "window.open.js": windowOpenScript,
+ },
+ };
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitMessage("setup-intermediate-tab");
+ yield* runTabReloadAndCloseTest(extension);
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_test.html b/toolkit/components/webextensions/test/mochitest/test_ext_test.html
new file mode 100644
index 000000000..fef31e0e2
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_test.html
@@ -0,0 +1,191 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Testing test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+function loadExtensionAndInterceptTest(extensionData) {
+ let results = [];
+ let testResolve;
+ let testDone = new Promise(resolve => { testResolve = resolve; });
+ let handler = {
+ testResult(...result) {
+ result.pop();
+ results.push(result);
+ SimpleTest.info(`Received test result: ${JSON.stringify(result)}`);
+ },
+
+ testMessage(msg, ...args) {
+ results.push(["test-message", msg, ...args]);
+ SimpleTest.info(`Received message: ${msg} ${JSON.stringify(args)}`);
+ if (msg === "This is the last browser.test call") {
+ testResolve();
+ }
+ },
+ };
+ let extension = SpecialPowers.loadExtension(extensionData, handler);
+ SimpleTest.registerCleanupFunction(() => {
+ if (extension.state == "pending" || extension.state == "running") {
+ SimpleTest.ok(false, "Extension left running at test shutdown");
+ return extension.unload();
+ } else if (extension.state == "unloading") {
+ SimpleTest.ok(false, "Extension not fully unloaded at test shutdown");
+ }
+ });
+ extension.awaitResults = () => testDone.then(() => results);
+ return extension;
+}
+
+function testScript() {
+ // Note: The result of these browser.test calls are intercepted by the test.
+ // See verifyTestResults for the expectations of each browser.test call.
+ browser.test.notifyPass("dot notifyPass");
+ browser.test.notifyFail("dot notifyFail");
+ browser.test.log("dot log");
+ browser.test.fail("dot fail");
+ browser.test.succeed("dot succeed");
+ browser.test.assertTrue(true);
+ browser.test.assertFalse(false);
+ browser.test.assertEq("", "");
+
+ let obj = {};
+ let arr = [];
+ let dom = document.createElement("body");
+ browser.test.assertTrue(obj, "Object truthy");
+ browser.test.assertTrue(arr, "Array truthy");
+ browser.test.assertTrue(dom, "Element truthy");
+ browser.test.assertTrue(true, "True truthy");
+ browser.test.assertTrue(false, "False truthy");
+ browser.test.assertTrue(null, "Null truthy");
+ browser.test.assertTrue(undefined, "Void truthy");
+ browser.test.assertTrue(false, document.createElement("html"));
+
+ browser.test.assertFalse(obj, "Object falsey");
+ browser.test.assertFalse(arr, "Array falsey");
+ browser.test.assertFalse(dom, "Element falsey");
+ browser.test.assertFalse(true, "True falsey");
+ browser.test.assertFalse(false, "False falsey");
+ browser.test.assertFalse(null, "Null falsey");
+ browser.test.assertFalse(undefined, "Void falsey");
+ browser.test.assertFalse(true, document.createElement("head"));
+
+ browser.test.assertEq(obj, obj, "Object equality");
+ browser.test.assertEq(arr, arr, "Array equality");
+ browser.test.assertEq(dom, dom, "Element equality");
+ browser.test.assertEq(null, null, "Null equality");
+ browser.test.assertEq(undefined, undefined, "Void equality");
+
+ browser.test.assertEq({}, {}, "Object reference ineqality");
+ browser.test.assertEq([], [], "Array reference ineqality");
+ browser.test.assertEq(dom, document.createElement("body"), "Element ineqality");
+ browser.test.assertEq(null, undefined, "Null and void ineqality");
+ browser.test.assertEq(true, false, document.createElement("div"));
+
+ obj = {
+ toString() {
+ return "Dynamic toString forbidden";
+ },
+ };
+ browser.test.assertEq(obj, obj, "obj with dynamic toString()");
+ browser.test.sendMessage("Ran test at", location.protocol);
+ browser.test.sendMessage("This is the last browser.test call");
+}
+
+function verifyTestResults(results, shortName, expectedProtocol) {
+ let expectations = [
+ ["test-done", true, "dot notifyPass"],
+ ["test-done", false, "dot notifyFail"],
+ ["test-log", true, "dot log"],
+ ["test-result", false, "dot fail"],
+ ["test-result", true, "dot succeed"],
+ ["test-result", true, "undefined"],
+ ["test-result", true, "undefined"],
+ ["test-eq", true, "undefined", "", ""],
+
+ ["test-result", true, "Object truthy"],
+ ["test-result", true, "Array truthy"],
+ ["test-result", true, "Element truthy"],
+ ["test-result", true, "True truthy"],
+ ["test-result", false, "False truthy"],
+ ["test-result", false, "Null truthy"],
+ ["test-result", false, "Void truthy"],
+ ["test-result", false, "[object HTMLHtmlElement]"],
+
+ ["test-result", false, "Object falsey"],
+ ["test-result", false, "Array falsey"],
+ ["test-result", false, "Element falsey"],
+ ["test-result", false, "True falsey"],
+ ["test-result", true, "False falsey"],
+ ["test-result", true, "Null falsey"],
+ ["test-result", true, "Void falsey"],
+ ["test-result", false, "[object HTMLHeadElement]"],
+
+ ["test-eq", true, "Object equality", "[object Object]", "[object Object]"],
+ ["test-eq", true, "Array equality", "", ""],
+ ["test-eq", true, "Element equality", "[object HTMLBodyElement]", "[object HTMLBodyElement]"],
+ ["test-eq", true, "Null equality", "null", "null"],
+ ["test-eq", true, "Void equality", "undefined", "undefined"],
+
+ ["test-eq", false, "Object reference ineqality", "[object Object]", "[object Object] (different)"],
+ ["test-eq", false, "Array reference ineqality", "", " (different)"],
+ ["test-eq", false, "Element ineqality", "[object HTMLBodyElement]", "[object HTMLBodyElement] (different)"],
+ ["test-eq", false, "Null and void ineqality", "null", "undefined"],
+ ["test-eq", false, "[object HTMLDivElement]", "true", "false"],
+
+ ["test-eq", true, "obj with dynamic toString()", "[object Object]", "[object Object]"],
+
+ ["test-message", "Ran test at", expectedProtocol],
+ ["test-message", "This is the last browser.test call"],
+ ];
+
+ expectations.forEach((expectation, i) => {
+ let msg = expectation.slice(2).join(" - ");
+ isDeeply(results[i], expectation, `${shortName} (${msg})`);
+ });
+ is(results[expectations.length], undefined, "No more results");
+}
+
+add_task(function* test_test_in_background() {
+ let extensionData = {
+ background: `(${testScript})()`,
+ };
+
+ let extension = loadExtensionAndInterceptTest(extensionData);
+ yield extension.startup();
+ let results = yield extension.awaitResults();
+ verifyTestResults(results, "background page", "moz-extension:");
+ yield extension.unload();
+});
+
+add_task(function* test_test_in_content_script() {
+ let extensionData = {
+ manifest: {
+ content_scripts: [{
+ matches: ["http://mochi.test/*/file_sample.html"],
+ js: ["contentscript.js"],
+ }],
+ },
+ files: {
+ "contentscript.js": `(${testScript})()`,
+ },
+ };
+
+ let extension = loadExtensionAndInterceptTest(extensionData);
+ yield extension.startup();
+ let win = window.open("file_sample.html");
+ let results = yield extension.awaitResults();
+ win.close();
+ verifyTestResults(results, "content script", "http:");
+ yield extension.unload();
+});
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html b/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html
new file mode 100644
index 000000000..5572de281
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html
@@ -0,0 +1,170 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>WebExtensions test</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">
+</head>
+<body>
+
+<script>
+"use strict";
+
+/* globals delayedNotifyPass */ // Available in the background page of the test extensions.
+
+// Background and content script for testSendMessage_*
+function sendMessage_background() {
+ browser.runtime.onMessage.addListener((msg, sender, sendResponse) => {
+ browser.test.assertEq("from frame", msg, "Expected message from frame");
+ sendResponse("msg from back"); // Should not throw or anything like that.
+ delayedNotifyPass("Received sendMessage from closing frame");
+ });
+}
+function sendMessage_contentScript(testType) {
+ browser.runtime.sendMessage("from frame", reply => {
+ // The frame has been removed, so we should not get this callback!
+ browser.test.fail(`Unexpected reply: ${reply}`);
+ });
+ if (testType == "frame") {
+ frameElement.remove();
+ } else {
+ window.close();
+ }
+}
+
+// Background and content script for testConnect_*
+function connect_background() {
+ browser.runtime.onConnect.addListener(port => {
+ browser.test.assertEq("port from frame", port.name);
+
+ let disconnected = false;
+ let hasMessage = false;
+ port.onDisconnect.addListener(() => {
+ browser.test.assertFalse(disconnected, "onDisconnect should fire once");
+ disconnected = true;
+ browser.test.assertTrue(hasMessage, "Expected onMessage before onDisconnect");
+ browser.test.assertEq(null, port.error, "The port is implicitly closed without errors when the other context unloads");
+ delayedNotifyPass("Received onDisconnect from closing frame");
+ });
+ port.onMessage.addListener(msg => {
+ browser.test.assertFalse(hasMessage, "onMessage should fire once");
+ hasMessage = true;
+ browser.test.assertFalse(disconnected, "Should get message before disconnect");
+ browser.test.assertEq("from frame", msg, "Expected message from frame");
+ });
+
+ port.postMessage("reply to closing frame");
+ });
+}
+function connect_contentScript(testType) {
+ let isUnloading = false;
+ addEventListener("pagehide", () => { isUnloading = true; }, {once: true});
+
+ let port = browser.runtime.connect({name: "port from frame"});
+ port.onMessage.addListener(msg => {
+ // The background page sends a reply as soon as we call runtime.connect().
+ // It is possible that the reply reaches this frame before the
+ // window.close() request has been processed.
+ if (!isUnloading) {
+ browser.test.log(`Ignorting unexpected reply ("${msg}") because the page is not being unloaded.`);
+ return;
+ }
+
+ // The frame has been removed, so we should not get a reply.
+ browser.test.fail(`Unexpected reply: ${msg}`);
+ });
+ port.postMessage("from frame");
+
+ // Removing the frame or window should disconnect the port.
+ if (testType == "frame") {
+ frameElement.remove();
+ } else {
+ window.close();
+ }
+}
+
+// `testType` is "window" or "frame".
+function createTestExtension(testType, backgroundScript, contentScript) {
+ // Make a roundtrip between the background page and the test runner (which is
+ // in the same process as the content script) to make sure that we record a
+ // failure in case the content script's sendMessage or onMessage handlers are
+ // called even after the frame or window was removed.
+ function delayedNotifyPass(msg) {
+ browser.test.onMessage.addListener((type, echoMsg) => {
+ if (type == "pong") {
+ browser.test.assertEq(msg, echoMsg, "Echoed reply should be the same");
+ browser.test.notifyPass(msg);
+ }
+ });
+ browser.test.log("Starting ping-pong to flush messages...");
+ browser.test.sendMessage("ping", msg);
+ }
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `${delayedNotifyPass};(${backgroundScript})();`,
+ manifest: {
+ content_scripts: [{
+ js: ["contentscript.js"],
+ all_frames: testType == "frame",
+ matches: ["http://mochi.test/*/file_sample.html"],
+ }],
+ },
+ files: {
+ "contentscript.js": `(${contentScript})("${testType}");`,
+ },
+ });
+ extension.awaitMessage("ping").then(msg => {
+ extension.sendMessage("pong", msg);
+ });
+ return extension;
+}
+
+add_task(function* testSendMessage_and_remove_frame() {
+ let extension = createTestExtension("frame", sendMessage_background, sendMessage_contentScript);
+ yield extension.startup();
+
+ let frame = document.createElement("iframe");
+ frame.src = "file_sample.html";
+ document.body.appendChild(frame);
+
+ yield extension.awaitFinish("Received sendMessage from closing frame");
+ yield extension.unload();
+});
+
+add_task(function* testConnect_and_remove_frame() {
+ let extension = createTestExtension("frame", connect_background, connect_contentScript);
+ yield extension.startup();
+
+ let frame = document.createElement("iframe");
+ frame.src = "file_sample.html";
+ document.body.appendChild(frame);
+
+ yield extension.awaitFinish("Received onDisconnect from closing frame");
+ yield extension.unload();
+});
+
+add_task(function* testSendMessage_and_remove_window() {
+ let extension = createTestExtension("window", sendMessage_background, sendMessage_contentScript);
+ yield extension.startup();
+
+ window.open("file_sample.html");
+
+ yield extension.awaitFinish("Received sendMessage from closing frame");
+ yield extension.unload();
+});
+
+add_task(function* testConnect_and_remove_window() {
+ let extension = createTestExtension("window", connect_background, connect_contentScript);
+ yield extension.startup();
+
+ window.open("file_sample.html");
+
+ yield extension.awaitFinish("Received onDisconnect from closing frame");
+ yield extension.unload();
+});
+
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html b/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html
new file mode 100644
index 000000000..fa3228739
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html
@@ -0,0 +1,353 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test the web_accessible_resources manifest directive</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* eslint-disable mozilla/balanced-listeners */
+
+SimpleTest.registerCleanupFunction(() => {
+ SpecialPowers.clearUserPref("security.mixed_content.block_display_content");
+});
+
+let image = atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAA" +
+ "ACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=");
+const IMAGE_ARRAYBUFFER = Uint8Array.from(image, byte => byte.charCodeAt(0)).buffer;
+
+async function testImageLoading(src, expectedAction) {
+ let imageLoadingPromise = new Promise((resolve, reject) => {
+ let cleanupListeners;
+ let testImage = document.createElement("img");
+ testImage.setAttribute("src", src);
+
+ let loadListener = () => {
+ cleanupListeners();
+ resolve(expectedAction === "loaded");
+ };
+
+ let errorListener = () => {
+ cleanupListeners();
+ resolve(expectedAction === "blocked");
+ };
+
+ cleanupListeners = () => {
+ testImage.removeEventListener("load", loadListener);
+ testImage.removeEventListener("error", errorListener);
+ };
+
+ testImage.addEventListener("load", loadListener);
+ testImage.addEventListener("error", errorListener);
+
+ document.body.appendChild(testImage);
+ });
+
+ let success = await imageLoadingPromise;
+ browser.runtime.sendMessage({name: "image-loading", expectedAction, success});
+}
+
+add_task(function* test_web_accessible_resources() {
+ function background() {
+ let gotURL;
+ let tabId;
+
+ function loadFrame(url) {
+ return new Promise(resolve => {
+ browser.tabs.sendMessage(tabId, ["load-iframe", url], reply => {
+ resolve(reply);
+ });
+ });
+ }
+
+ let urls = [
+ [browser.extension.getURL("accessible.html"), true],
+ [browser.extension.getURL("accessible.html") + "?foo=bar", true],
+ [browser.extension.getURL("accessible.html") + "#!foo=bar", true],
+ [browser.extension.getURL("forbidden.html"), false],
+ [browser.extension.getURL("wild1.html"), true],
+ [browser.extension.getURL("wild2.htm"), false],
+ ];
+
+ async function runTests() {
+ for (let [url, shouldLoad] of urls) {
+ let success = await loadFrame(url);
+
+ browser.test.assertEq(shouldLoad, success, "Load was successful");
+ if (shouldLoad) {
+ browser.test.assertEq(url, gotURL, "Got expected url");
+ } else {
+ browser.test.assertEq(undefined, gotURL, "Got no url");
+ }
+ gotURL = undefined;
+ }
+
+ browser.test.notifyPass("web-accessible-resources");
+ }
+
+ browser.runtime.onMessage.addListener(([msg, url], sender) => {
+ if (msg == "content-script-ready") {
+ tabId = sender.tab.id;
+ runTests();
+ } else if (msg == "page-script") {
+ browser.test.assertEq(undefined, gotURL, "Should have gotten only one message");
+ browser.test.assertEq("string", typeof(url), "URL should be a string");
+ gotURL = url;
+ }
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ function contentScript() {
+ browser.runtime.onMessage.addListener(([msg, url], sender, respond) => {
+ if (msg == "load-iframe") {
+ let iframe = document.createElement("iframe");
+ iframe.setAttribute("src", url);
+ iframe.addEventListener("load", () => { respond(true); });
+ iframe.addEventListener("error", () => { respond(false); });
+ document.body.appendChild(iframe);
+ return true;
+ }
+ });
+ browser.runtime.sendMessage(["content-script-ready"]);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://example.com/"],
+ "js": ["content_script.js"],
+ "run_at": "document_idle",
+ },
+ ],
+
+ "web_accessible_resources": [
+ "/accessible.html",
+ "wild*.html",
+ ],
+ },
+
+ background,
+
+ files: {
+ "content_script.js": contentScript,
+
+ "accessible.html": `<html><head>
+ <meta charset="utf-8">
+ <script src="accessible.js"><\/script>
+ </head></html>`,
+
+ "accessible.js": 'browser.runtime.sendMessage(["page-script", location.href]);',
+
+ "inaccessible.html": `<html><head>
+ <meta charset="utf-8">
+ <script src="inaccessible.js"><\/script>
+ </head></html>`,
+
+ "inaccessible.js": 'browser.runtime.sendMessage(["page-script", location.href]);',
+
+ "wild1.html": `<html><head>
+ <meta charset="utf-8">
+ <script src="wild.js"><\/script>
+ </head></html>`,
+
+ "wild2.htm": `<html><head>
+ <meta charset="utf-8">
+ <script src="wild.js"><\/script>
+ </head></html>`,
+
+ "wild.js": 'browser.runtime.sendMessage(["page-script", location.href]);',
+ },
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitMessage("ready");
+
+ let win = window.open("http://example.com/");
+
+ yield extension.awaitFinish("web-accessible-resources");
+
+ win.close();
+
+ yield extension.unload();
+});
+
+add_task(function* test_web_accessible_resources_csp() {
+ function background() {
+ browser.runtime.onMessage.addListener((msg, sender) => {
+ if (msg.name === "image-loading") {
+ browser.test.assertTrue(msg.success, `Image was ${msg.expectedAction}`);
+ browser.test.sendMessage(`image-${msg.expectedAction}`);
+ } else {
+ browser.test.sendMessage(msg);
+ }
+ });
+
+ browser.test.sendMessage("background-ready");
+ }
+
+ function content() {
+ window.addEventListener("message", function rcv(event) {
+ browser.runtime.sendMessage("script-ran");
+ window.removeEventListener("message", rcv, false);
+ }, false);
+
+ testImageLoading(browser.extension.getURL("image.png"), "loaded");
+
+ let testScriptElement = document.createElement("script");
+ testScriptElement.setAttribute("src", browser.extension.getURL("test_script.js"));
+ document.head.appendChild(testScriptElement);
+ browser.runtime.sendMessage("script-loaded");
+ }
+
+ function testScript() {
+ window.postMessage("test-script-loaded", "*");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["http://example.com/*/file_csp.html"],
+ "run_at": "document_start",
+ "js": ["content_script_helper.js", "content_script.js"],
+ }],
+ "web_accessible_resources": [
+ "image.png",
+ "test_script.js",
+ ],
+ },
+ background,
+ files: {
+ "content_script_helper.js": `${testImageLoading}`,
+ "content_script.js": content,
+ "test_script.js": testScript,
+ "image.png": IMAGE_ARRAYBUFFER,
+ },
+ });
+
+ // This is used to watch the blocked data bounce off CSP.
+ function examiner() {
+ SpecialPowers.addObserver(this, "csp-on-violate-policy", false);
+ }
+
+ let cspEventCount = 0;
+
+ examiner.prototype = {
+ observe: function(subject, topic, data) {
+ cspEventCount++;
+ let spec = SpecialPowers.wrap(subject).QueryInterface(SpecialPowers.Ci.nsIURI).spec;
+ ok(spec.includes("file_image_bad.png") || spec.includes("file_script_bad.js"),
+ `Expected file: ${spec} rejected by CSP`);
+ },
+
+ // We must eventually call this to remove the listener,
+ // or mochitests might get borked.
+ remove: function() {
+ SpecialPowers.removeObserver(this, "csp-on-violate-policy");
+ },
+ };
+
+ let observer = new examiner();
+
+ yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]);
+
+ let win = window.open("http://example.com/tests/toolkit/components/extensions/test/mochitest/file_csp.html");
+
+ yield Promise.all([
+ extension.awaitMessage("image-loaded"),
+ extension.awaitMessage("script-loaded"),
+ extension.awaitMessage("script-ran"),
+ ]);
+ is(cspEventCount, 2, "Two items were rejected by CSP");
+ win.close();
+
+ observer.remove();
+ yield extension.unload();
+});
+
+add_task(function* test_web_accessible_resources_mixed_content() {
+ function background() {
+ browser.runtime.onMessage.addListener(msg => {
+ if (msg.name === "image-loading") {
+ browser.test.assertTrue(msg.success, `Image was ${msg.expectedAction}`);
+ browser.test.sendMessage(`image-${msg.expectedAction}`);
+ } else {
+ browser.test.sendMessage(msg);
+ if (msg === "accessible-script-loaded") {
+ browser.test.notifyPass("mixed-test");
+ }
+ }
+ });
+
+ browser.test.sendMessage("background-ready");
+ }
+
+ function content() {
+ testImageLoading("http://example.com/tests/toolkit/components/extensions/test/mochitest/file_image_bad.png", "blocked");
+ testImageLoading(browser.extension.getURL("image.png"), "loaded");
+
+ let testScriptElement = document.createElement("script");
+ testScriptElement.setAttribute("src", browser.extension.getURL("test_script.js"));
+ document.head.appendChild(testScriptElement);
+
+ window.addEventListener("message", event => {
+ browser.runtime.sendMessage(event.data);
+ });
+ }
+
+ function testScript() {
+ window.postMessage("accessible-script-loaded", "*");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "content_scripts": [{
+ "matches": ["https://example.com/*/file_mixed.html"],
+ "run_at": "document_start",
+ "js": ["content_script_helper.js", "content_script.js"],
+ }],
+ "web_accessible_resources": [
+ "image.png",
+ "test_script.js",
+ ],
+ },
+ background,
+ files: {
+ "content_script_helper.js": `${testImageLoading}`,
+ "content_script.js": content,
+ "test_script.js": testScript,
+ "image.png": IMAGE_ARRAYBUFFER,
+ },
+ });
+
+ SpecialPowers.setBoolPref("security.mixed_content.block_display_content", true);
+
+ yield Promise.all([extension.startup(), extension.awaitMessage("background-ready")]);
+
+ let win = window.open("https://example.com/tests/toolkit/components/extensions/test/mochitest/file_mixed.html");
+
+ yield Promise.all([
+ extension.awaitMessage("image-blocked"),
+ extension.awaitMessage("image-loaded"),
+ extension.awaitMessage("accessible-script-loaded"),
+ ]);
+ yield extension.awaitFinish("mixed-test");
+ win.close();
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html
new file mode 100644
index 000000000..2287fd9b1
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html
@@ -0,0 +1,559 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* globals sendMouseEvent */
+
+function backgroundScript() {
+ const BASE = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest";
+ const URL = BASE + "/file_WebNavigation_page1.html";
+
+ const EVENTS = [
+ "onTabReplaced",
+ "onBeforeNavigate",
+ "onCommitted",
+ "onDOMContentLoaded",
+ "onCompleted",
+ "onErrorOccurred",
+ "onReferenceFragmentUpdated",
+ "onHistoryStateUpdated",
+ ];
+
+ let expectedTabId = -1;
+
+ function gotEvent(event, details) {
+ if (!details.url.startsWith(BASE)) {
+ return;
+ }
+ browser.test.log(`Got ${event} ${details.url} ${details.frameId} ${details.parentFrameId}`);
+
+ if (expectedTabId == -1) {
+ browser.test.assertTrue(details.tabId !== undefined, "tab ID defined");
+ expectedTabId = details.tabId;
+ }
+
+ browser.test.assertEq(details.tabId, expectedTabId, "correct tab");
+
+ browser.test.sendMessage("received", {url: details.url, event});
+
+ if (details.url == URL) {
+ browser.test.assertEq(details.frameId, 0, "root frame ID correct");
+ browser.test.assertEq(details.parentFrameId, -1, "root parent frame ID correct");
+ } else {
+ browser.test.assertEq(details.parentFrameId, 0, "parent frame ID correct");
+ browser.test.assertTrue(details.frameId != 0, "frame ID probably okay");
+ }
+
+ browser.test.assertTrue(details.frameId !== undefined);
+ browser.test.assertTrue(details.parentFrameId !== undefined);
+ }
+
+ let listeners = {};
+ for (let event of EVENTS) {
+ listeners[event] = gotEvent.bind(null, event);
+ browser.webNavigation[event].addListener(listeners[event]);
+ }
+
+ browser.test.sendMessage("ready");
+}
+
+const BASE = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest";
+const URL = BASE + "/file_WebNavigation_page1.html";
+const FRAME = BASE + "/file_WebNavigation_page2.html";
+const FRAME2 = BASE + "/file_WebNavigation_page3.html";
+const FRAME_PUSHSTATE = BASE + "/file_WebNavigation_page3_pushState.html";
+const REDIRECT = BASE + "/redirection.sjs";
+const REDIRECTED = BASE + "/dummy_page.html";
+const CLIENT_REDIRECT = BASE + "/file_webNavigation_clientRedirect.html";
+const CLIENT_REDIRECT_HTTPHEADER = BASE + "/file_webNavigation_clientRedirect_httpHeaders.html";
+const FRAME_CLIENT_REDIRECT = BASE + "/file_webNavigation_frameClientRedirect.html";
+const FRAME_REDIRECT = BASE + "/file_webNavigation_frameRedirect.html";
+const FRAME_MANUAL = BASE + "/file_webNavigation_manualSubframe.html";
+const FRAME_MANUAL_PAGE1 = BASE + "/file_webNavigation_manualSubframe_page1.html";
+const FRAME_MANUAL_PAGE2 = BASE + "/file_webNavigation_manualSubframe_page2.html";
+const INVALID_PAGE = "https://invalid.localhost/";
+
+const REQUIRED = [
+ "onBeforeNavigate",
+ "onCommitted",
+ "onDOMContentLoaded",
+ "onCompleted",
+];
+
+var received = [];
+var completedResolve;
+var waitingURL, waitingEvent;
+
+function loadAndWait(win, event, url, script) {
+ received = [];
+ waitingEvent = event;
+ waitingURL = url;
+ dump(`RUN ${script}\n`);
+ script();
+ return new Promise(resolve => { completedResolve = resolve; });
+}
+
+add_task(function* webnav_transitions_props() {
+ function backgroundScriptTransitions() {
+ const EVENTS = [
+ "onCommitted",
+ "onCompleted",
+ ];
+
+ function gotEvent(event, details) {
+ browser.test.log(`Got ${event} ${details.url} ${details.transitionType} ${details.transitionQualifiers && JSON.stringify(details.transitionQualifiers)}`);
+
+ browser.test.sendMessage("received", {url: details.url, details, event});
+ }
+
+ let listeners = {};
+ for (let event of EVENTS) {
+ listeners[event] = gotEvent.bind(null, event);
+ browser.webNavigation[event].addListener(listeners[event]);
+ }
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extensionData = {
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background: backgroundScriptTransitions,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ extension.onMessage("received", ({url, event, details}) => {
+ received.push({url, event, details});
+
+ if (event == waitingEvent && url == waitingURL) {
+ completedResolve();
+ }
+ });
+
+ yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
+ info("webnavigation extension loaded");
+
+ let win = window.open();
+
+ yield loadAndWait(win, "onCompleted", URL, () => { win.location = URL; });
+
+ // transitionType: reload
+ received = [];
+ yield loadAndWait(win, "onCompleted", URL, () => { win.location.reload(); });
+
+ let found = received.find((data) => (data.event == "onCommitted" && data.url == URL));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "reload",
+ "Got the expected 'reload' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers),
+ "transitionQualifiers found in the OnCommitted events");
+ }
+
+ // transitionType: auto_subframe
+ found = received.find((data) => (data.event == "onCommitted" && data.url == FRAME));
+
+ ok(found, "Got the sub-frame onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "auto_subframe",
+ "Got the expected 'auto_subframe' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers),
+ "transitionQualifiers found in the OnCommitted events");
+ }
+
+ // transitionType: form_submit
+ received = [];
+ yield loadAndWait(win, "onCompleted", URL, () => {
+ win.document.querySelector("form").submit();
+ });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == URL));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "form_submit",
+ "Got the expected 'form_submit' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers),
+ "transitionQualifiers found in the OnCommitted events");
+ }
+
+ // transitionQualifier: server_redirect
+ received = [];
+ yield loadAndWait(win, "onCompleted", REDIRECTED, () => { win.location = REDIRECT; });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == REDIRECTED));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "link",
+ "Got the expected 'link' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers) &&
+ found.details.transitionQualifiers.find((q) => q == "server_redirect"),
+ "Got the expected 'server_redirect' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionQualifier: forward_back
+ received = [];
+ yield loadAndWait(win, "onCompleted", URL, () => { win.history.back(); });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == URL));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "link",
+ "Got the expected 'link' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers) &&
+ found.details.transitionQualifiers.find((q) => q == "forward_back"),
+ "Got the expected 'forward_back' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionQualifier: client_redirect
+ // (from meta http-equiv tag)
+ received = [];
+ yield loadAndWait(win, "onCompleted", REDIRECTED, () => {
+ win.location = CLIENT_REDIRECT;
+ });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == REDIRECTED));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "link",
+ "Got the expected 'link' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers) &&
+ found.details.transitionQualifiers.find((q) => q == "client_redirect"),
+ "Got the expected 'client_redirect' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionQualifier: client_redirect
+ // (from http headers)
+ received = [];
+ yield loadAndWait(win, "onCompleted", REDIRECTED, () => {
+ win.location = CLIENT_REDIRECT_HTTPHEADER;
+ });
+
+ found = received.find((data) => (data.event == "onCommitted" &&
+ data.url == CLIENT_REDIRECT_HTTPHEADER));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "link",
+ "Got the expected 'link' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers) &&
+ found.details.transitionQualifiers.find((q) => q == "client_redirect"),
+ "Got the expected 'client_redirect' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionQualifier: client_redirect (sub-frame)
+ // (from meta http-equiv tag)
+ received = [];
+ yield loadAndWait(win, "onCompleted", REDIRECTED, () => {
+ win.location = FRAME_CLIENT_REDIRECT;
+ });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == REDIRECTED));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "auto_subframe",
+ "Got the expected 'auto_subframe' transitionType in the OnCommitted event");
+ ok(Array.isArray(found.details.transitionQualifiers) &&
+ found.details.transitionQualifiers.find((q) => q == "client_redirect"),
+ "Got the expected 'client_redirect' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionQualifier: server_redirect (sub-frame)
+ received = [];
+ yield loadAndWait(win, "onCompleted", REDIRECTED, () => { win.location = FRAME_REDIRECT; });
+
+ found = received.find((data) => (data.event == "onCommitted" && data.url == REDIRECT));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "auto_subframe",
+ "Got the expected 'auto_subframe' transitionType in the OnCommitted event");
+ // BUG 1264936: currently the server_redirect is not detected in sub-frames
+ // once we fix it we can test it here:
+ //
+ // ok(Array.isArray(found.details.transitionQualifiers) &&
+ // found.details.transitionQualifiers.find((q) => q == "server_redirect"),
+ // "Got the expected 'server_redirect' transitionQualifiers in the OnCommitted events");
+ }
+
+ // transitionType: manual_subframe
+ received = [];
+ yield loadAndWait(win, "onCompleted", FRAME_MANUAL, () => { win.location = FRAME_MANUAL; });
+ found = received.find((data) => (data.event == "onCommitted" &&
+ data.url == FRAME_MANUAL_PAGE1));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "auto_subframe",
+ "Got the expected 'auto_subframe' transitionType in the OnCommitted event");
+ }
+
+ received = [];
+ yield loadAndWait(win, "onCompleted", FRAME_MANUAL_PAGE2, () => {
+ let el = win.document.querySelector("iframe")
+ .contentDocument.querySelector("a");
+ sendMouseEvent({type: "click"}, el, win);
+ });
+
+ found = received.find((data) => (data.event == "onCommitted" &&
+ data.url == FRAME_MANUAL_PAGE2));
+
+ ok(found, "Got the onCommitted event");
+
+ if (found) {
+ is(found.details.transitionType, "manual_subframe",
+ "Got the expected 'manual_subframe' transitionType in the OnCommitted event");
+ }
+
+ // cleanup phase
+ win.close();
+
+ yield extension.unload();
+ info("webnavigation extension unloaded");
+});
+
+add_task(function* webnav_ordering() {
+ let extensionData = {
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background: backgroundScript,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ extension.onMessage("received", ({url, event}) => {
+ received.push({url, event});
+
+ if (event == waitingEvent && url == waitingURL) {
+ completedResolve();
+ }
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+ info("webnavigation extension loaded");
+
+ let win = window.open();
+
+ yield loadAndWait(win, "onCompleted", URL, () => { win.location = URL; });
+
+ function checkRequired(url) {
+ for (let event of REQUIRED) {
+ let found = false;
+ for (let r of received) {
+ if (r.url == url && r.event == event) {
+ found = true;
+ }
+ }
+ ok(found, `Received event ${event} from ${url}`);
+ }
+ }
+
+ checkRequired(URL);
+ checkRequired(FRAME);
+
+ function checkBefore(action1, action2) {
+ function find(action) {
+ for (let i = 0; i < received.length; i++) {
+ if (received[i].url == action.url && received[i].event == action.event) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ let index1 = find(action1);
+ let index2 = find(action2);
+ ok(index1 != -1, `Action ${JSON.stringify(action1)} happened`);
+ ok(index2 != -1, `Action ${JSON.stringify(action2)} happened`);
+ ok(index1 < index2, `Action ${JSON.stringify(action1)} happened before ${JSON.stringify(action2)}`);
+ }
+
+ // As required in the webNavigation API documentation:
+ // If a navigating frame contains subframes, its onCommitted is fired before any
+ // of its children's onBeforeNavigate; while onCompleted is fired after
+ // all of its children's onCompleted.
+ checkBefore({url: URL, event: "onCommitted"}, {url: FRAME, event: "onBeforeNavigate"});
+ checkBefore({url: FRAME, event: "onCompleted"}, {url: URL, event: "onCompleted"});
+
+ // As required in the webNAvigation API documentation, check the event sequence:
+ // onBeforeNavigate -> onCommitted -> onDOMContentLoaded -> onCompleted
+ let expectedEventSequence = [
+ "onBeforeNavigate", "onCommitted", "onDOMContentLoaded", "onCompleted",
+ ];
+
+ for (let i = 1; i < expectedEventSequence.length; i++) {
+ let after = expectedEventSequence[i];
+ let before = expectedEventSequence[i - 1];
+ checkBefore({url: URL, event: before}, {url: URL, event: after});
+ checkBefore({url: FRAME, event: before}, {url: FRAME, event: after});
+ }
+
+ yield loadAndWait(win, "onCompleted", FRAME2, () => { win.frames[0].location = FRAME2; });
+
+ checkRequired(FRAME2);
+
+ let navigationSequence = [
+ {
+ action: () => { win.frames[0].document.getElementById("elt").click(); },
+ waitURL: `${FRAME2}#ref`,
+ expectedEvent: "onReferenceFragmentUpdated",
+ description: "clicked an anchor link",
+ },
+ {
+ action: () => { win.frames[0].history.pushState({}, "History PushState", `${FRAME2}#ref2`); },
+ waitURL: `${FRAME2}#ref2`,
+ expectedEvent: "onReferenceFragmentUpdated",
+ description: "history.pushState, same pathname, different hash",
+ },
+ {
+ action: () => { win.frames[0].history.pushState({}, "History PushState", `${FRAME2}#ref2`); },
+ waitURL: `${FRAME2}#ref2`,
+ expectedEvent: "onHistoryStateUpdated",
+ description: "history.pushState, same pathname, same hash",
+ },
+ {
+ action: () => {
+ win.frames[0].history.pushState({}, "History PushState", `${FRAME2}?query_param1=value#ref2`);
+ },
+ waitURL: `${FRAME2}?query_param1=value#ref2`,
+ expectedEvent: "onHistoryStateUpdated",
+ description: "history.pushState, same pathname, same hash, different query params",
+ },
+ {
+ action: () => {
+ win.frames[0].history.pushState({}, "History PushState", `${FRAME2}?query_param2=value#ref3`);
+ },
+ waitURL: `${FRAME2}?query_param2=value#ref3`,
+ expectedEvent: "onHistoryStateUpdated",
+ description: "history.pushState, same pathname, different hash, different query params",
+ },
+ {
+ action: () => { win.frames[0].history.pushState(null, "History PushState", FRAME_PUSHSTATE); },
+ waitURL: FRAME_PUSHSTATE,
+ expectedEvent: "onHistoryStateUpdated",
+ description: "history.pushState, different pathname",
+ },
+ ];
+
+ for (let navigation of navigationSequence) {
+ let {expectedEvent, waitURL, action, description} = navigation;
+ info(`Waiting ${expectedEvent} from ${waitURL} - ${description}`);
+ yield loadAndWait(win, expectedEvent, waitURL, action);
+ info(`Received ${expectedEvent} from ${waitURL} - ${description}`);
+ }
+
+ for (let i = navigationSequence.length - 1; i > 0; i--) {
+ let {waitURL: fromURL, expectedEvent} = navigationSequence[i];
+ let {waitURL} = navigationSequence[i - 1];
+ info(`Waiting ${expectedEvent} from ${waitURL} - history.back() from ${fromURL} to ${waitURL}`);
+ yield loadAndWait(win, expectedEvent, waitURL, () => { win.frames[0].history.back(); });
+ info(`Received ${expectedEvent} from ${waitURL} - history.back() from ${fromURL} to ${waitURL}`);
+ }
+
+ for (let i = 0; i < navigationSequence.length - 1; i++) {
+ let {waitURL: fromURL} = navigationSequence[i];
+ let {waitURL, expectedEvent} = navigationSequence[i + 1];
+ info(`Waiting ${expectedEvent} from ${waitURL} - history.forward() from ${fromURL} to ${waitURL}`);
+ yield loadAndWait(win, expectedEvent, waitURL, () => { win.frames[0].history.forward(); });
+ info(`Received ${expectedEvent} from ${waitURL} - history.forward() from ${fromURL} to ${waitURL}`);
+ }
+
+ win.close();
+
+ yield extension.unload();
+ info("webnavigation extension unloaded");
+});
+
+add_task(function* webnav_error_event() {
+ function backgroundScriptErrorEvent() {
+ browser.webNavigation.onErrorOccurred.addListener((details) => {
+ browser.test.log(`Got onErrorOccurred ${details.url} ${details.error}`);
+
+ browser.test.sendMessage("received", {url: details.url, details, event: "onErrorOccurred"});
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extensionData = {
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background: backgroundScriptErrorEvent,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ extension.onMessage("received", ({url, event, details}) => {
+ received.push({url, event, details});
+
+ if (event == waitingEvent && url == waitingURL) {
+ completedResolve();
+ }
+ });
+
+ yield Promise.all([extension.startup(), extension.awaitMessage("ready")]);
+ info("webnavigation extension loaded");
+
+ let win = window.open();
+
+ received = [];
+ yield loadAndWait(win, "onErrorOccurred", INVALID_PAGE, () => { win.location = INVALID_PAGE; });
+
+ let found = received.find((data) => (data.event == "onErrorOccurred" &&
+ data.url == INVALID_PAGE));
+
+ ok(found, "Got the onErrorOccurred event");
+
+ if (found) {
+ ok(found.details.error.match(/Error code [0-9]+/),
+ "Got the expected error string in the onErrorOccurred event");
+ }
+
+ // cleanup phase
+ win.close();
+
+ yield extension.unload();
+ info("webnavigation extension unloaded");
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html
new file mode 100644
index 000000000..a0de5e9e5
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html
@@ -0,0 +1,308 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_webnav_unresolved_uri_on_expected_URI_scheme() {
+ function background() {
+ let lastTest;
+
+ function cleanupTestListeners() {
+ if (lastTest) {
+ let {event, okListener, failListener} = lastTest;
+ lastTest = null;
+ browser.test.log(`Cleanup previous test event listeners`);
+ browser.webNavigation[event].removeListener(okListener);
+ browser.webNavigation[event].removeListener(failListener);
+ }
+ }
+
+ function createTestListener(event, fail, urlFilter) {
+ function listener(details) {
+ let log = JSON.stringify({url: details.url, urlFilter});
+ if (fail) {
+ browser.test.fail(`Got an unexpected ${event} on the failure listener: ${log}`);
+ } else {
+ browser.test.succeed(`Got the expected ${event} on the success listener: ${log}`);
+ }
+
+ cleanupTestListeners();
+ browser.test.sendMessage("test-filter-next");
+ }
+
+ browser.webNavigation[event].addListener(listener, urlFilter);
+
+ return listener;
+ }
+
+ browser.test.onMessage.addListener((msg, event, okFilter, failFilter) => {
+ if (msg !== "test-filter") {
+ return;
+ }
+
+ lastTest = {
+ event,
+ // Register the failListener first, which should not be called
+ // and if it is called the test scenario is marked as a failure.
+ failListener: createTestListener(event, true, failFilter),
+ okListener: createTestListener(event, false, okFilter),
+ };
+
+ browser.test.sendMessage("test-filter-ready");
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extensionData = {
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ yield extension.awaitMessage("ready");
+
+ let win = window.open();
+
+ let testFilterScenarios = [
+ {
+ url: "http://example.net/browser",
+ filters: [
+ // schemes
+ {
+ okFilter: [{schemes: ["http"]}],
+ failFilter: [{schemes: ["https"]}],
+ },
+ // ports
+ {
+ okFilter: [{ports: [80, 22, 443]}],
+ failFilter: [{ports: [81, 82, 83]}],
+ },
+ {
+ okFilter: [{ports: [22, 443, [10, 80]]}],
+ failFilter: [{ports: [22, 23, [81, 100]]}],
+ },
+ ],
+ },
+ {
+ url: "http://example.net/browser?param=1#ref",
+ filters: [
+ // host: Equals, Contains, Prefix, Suffix
+ {
+ okFilter: [{hostEquals: "example.net"}],
+ failFilter: [{hostEquals: "example.com"}],
+ },
+ {
+ okFilter: [{hostContains: ".example"}],
+ failFilter: [{hostContains: ".www"}],
+ },
+ {
+ okFilter: [{hostPrefix: "example"}],
+ failFilter: [{hostPrefix: "www"}],
+ },
+ {
+ okFilter: [{hostSuffix: "net"}],
+ failFilter: [{hostSuffix: "com"}],
+ },
+ // path: Equals, Contains, Prefix, Suffix
+ {
+ okFilter: [{pathEquals: "/browser"}],
+ failFilter: [{pathEquals: "/"}],
+ },
+ {
+ okFilter: [{pathContains: "brow"}],
+ failFilter: [{pathContains: "tool"}],
+ },
+ {
+ okFilter: [{pathPrefix: "/bro"}],
+ failFilter: [{pathPrefix: "/tool"}],
+ },
+ {
+ okFilter: [{pathSuffix: "wser"}],
+ failFilter: [{pathSuffix: "kit"}],
+ },
+ // query: Equals, Contains, Prefix, Suffix
+ {
+ okFilter: [{queryEquals: "param=1"}],
+ failFilter: [{queryEquals: "wrongparam=2"}],
+ },
+ {
+ okFilter: [{queryContains: "param"}],
+ failFilter: [{queryContains: "wrongparam"}],
+ },
+ {
+ okFilter: [{queryPrefix: "param="}],
+ failFilter: [{queryPrefix: "wrong"}],
+ },
+ {
+ okFilter: [{querySuffix: "=1"}],
+ failFilter: [{querySuffix: "=2"}],
+ },
+ // urlMatches, originAndPathMatches
+ {
+ okFilter: [{urlMatches: "example.net/.*\?param=1"}],
+ failFilter: [{urlMatches: "example.net/.*\?wrongparam=2"}],
+ },
+ {
+ okFilter: [{originAndPathMatches: "example.net\/browser"}],
+ failFilter: [{originAndPathMatches: "example.net/.*\?param=1"}],
+ },
+ ],
+ },
+ {
+ url: "http://example.net/browser",
+ filters: [
+ // multiple criteria in a single filter:
+ // if one of the critera is not verified, the event should not be received.
+ {
+ okFilter: [{schemes: ["http"], ports: [80, 22, 443]}],
+ failFilter: [{schemes: ["http"], ports: [81, 82, 83]}],
+ },
+ // multiple urlFilters on the same listener
+ // if at least one of the critera is verified, the event should be received.
+ {
+ okFilter: [{schemes: ["https"]}, {ports: [80, 22, 443]}],
+ failFilter: [{schemes: ["https"]}, {ports: [81, 82, 83]}],
+ },
+ ],
+ },
+ ];
+
+ function* runTestScenario(event, {url, filters}) {
+ for (let testFilters of filters) {
+ let {okFilter, failFilter} = testFilters;
+
+ info(`Prepare the new test scenario: ${event} ${url} ${JSON.stringify(testFilters)}`);
+ win.location = "about:blank";
+
+ extension.sendMessage("test-filter", event, {url: okFilter}, {url: failFilter});
+ yield extension.awaitMessage("test-filter-ready");
+
+ info(`Loading the test url: ${url}`);
+ win.location = url;
+
+ yield extension.awaitMessage("test-filter-next");
+
+ info("Test scenario completed. Moving to the next test scenario.");
+ }
+ }
+
+ const BASE_WEBNAV_EVENTS = [
+ "onBeforeNavigate",
+ "onCommitted",
+ "onDOMContentLoaded",
+ "onCompleted",
+ ];
+
+ info("WebNavigation event filters test scenarios starting...");
+
+ for (let filterScenario of testFilterScenarios) {
+ for (let event of BASE_WEBNAV_EVENTS) {
+ yield runTestScenario(event, filterScenario);
+ }
+ }
+
+ info("WebNavigation event filters test onReferenceFragmentUpdated scenario starting...");
+
+ const BASE = "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest";
+ let url = BASE + "/file_WebNavigation_page3.html";
+
+ let okFilter = [{urlContains: "_page3.html"}];
+ let failFilter = [{ports: [444]}];
+ let event = "onCompleted";
+
+ info(`Loading the initial test url: ${url}`);
+ extension.sendMessage("test-filter", event, {url: okFilter}, {url: failFilter});
+
+ yield extension.awaitMessage("test-filter-ready");
+ win.location = url;
+ yield extension.awaitMessage("test-filter-next");
+
+ event = "onReferenceFragmentUpdated";
+ extension.sendMessage("test-filter", event, {url: okFilter}, {url: failFilter});
+
+ yield extension.awaitMessage("test-filter-ready");
+ win.location = url + "#ref1";
+ yield extension.awaitMessage("test-filter-next");
+
+ info("WebNavigation event filters test onHistoryStateUpdated scenario starting...");
+
+ event = "onHistoryStateUpdated";
+ extension.sendMessage("test-filter", event, {url: okFilter}, {url: failFilter});
+ yield extension.awaitMessage("test-filter-ready");
+
+ win.history.pushState({}, "", BASE + "/pushState_page3.html");
+ yield extension.awaitMessage("test-filter-next");
+
+ // TODO: add additional specific tests for the other webNavigation events:
+ // onErrorOccurred (and onCreatedNavigationTarget on supported)
+
+ info("WebNavigation event filters test scenarios completed.");
+
+ yield extension.unload();
+
+ win.close();
+});
+
+add_task(function* test_webnav_empty_filter_validation_error() {
+ function background() {
+ let catchedException;
+
+ try {
+ browser.webNavigation.onCompleted.addListener(
+ // Empty callback (not really used)
+ () => {},
+ // Empty filter (which should raise a validation error exception).
+ {url: []}
+ );
+ } catch (e) {
+ catchedException = e;
+ browser.test.log(`Got an exception`);
+ }
+
+ if (catchedException &&
+ catchedException.message.includes("Type error for parameter filters") &&
+ catchedException.message.includes("Array requires at least 1 items; you have 0")) {
+ browser.test.notifyPass("webNav.emptyFilterValidationError");
+ } else {
+ browser.test.notifyFail("webNav.emptyFilterValidationError");
+ }
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webNavigation",
+ ],
+ },
+ background,
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("webNav.emptyFilterValidationError");
+
+ yield extension.unload();
+});
+
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html
new file mode 100644
index 000000000..78efeab35
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html
@@ -0,0 +1,116 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_webRequest_serviceworker_events() {
+ yield SpecialPowers.pushPrefEnv({
+ set: [["dom.serviceWorkers.testing.enabled", true],
+ ["dom.serviceWorkers.enabled", true],
+ ["dom.serviceWorkers.openWindow.enabled", true],
+ ],
+ });
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "<all_urls>",
+ ],
+ },
+ background() {
+ let eventNames = new Set([
+ "onBeforeRequest",
+ "onBeforeSendHeaders",
+ "onSendHeaders",
+ "onHeadersReceived",
+ "onResponseStarted",
+ "onCompleted",
+ ]);
+
+ function listener(name, details) {
+ browser.test.assertTrue(eventNames.has(name), `recieved ${name}`);
+ eventNames.delete(name);
+ if (eventNames.size == 0) {
+ browser.test.sendMessage("done");
+ }
+ }
+
+ for (let name of eventNames) {
+ browser.webRequest[name].addListener(
+ listener.bind(null, name),
+ {urls: ["https://example.com/*"]}
+ );
+ }
+ },
+ });
+
+ yield extension.startup();
+ let registration = yield navigator.serviceWorker.register("webrequest_worker.js", {scope: "."});
+ yield extension.awaitMessage("done");
+ yield registration.unregister();
+ yield extension.unload();
+});
+
+add_task(function* test_webRequest_background_events() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "<all_urls>",
+ ],
+ },
+ background() {
+ let eventNames = new Set([
+ "onBeforeRequest",
+ "onBeforeSendHeaders",
+ "onSendHeaders",
+ "onHeadersReceived",
+ "onResponseStarted",
+ "onCompleted",
+ ]);
+
+ function listener(name, details) {
+ browser.test.assertTrue(eventNames.has(name), `recieved ${name}`);
+ eventNames.delete(name);
+
+ if (eventNames.size === 0) {
+ browser.test.assertEq(0, eventNames.size, "messages recieved");
+ browser.test.sendMessage("done");
+ }
+ }
+
+ for (let name of eventNames) {
+ browser.webRequest[name].addListener(
+ listener.bind(null, name),
+ {urls: ["https://example.com/*"]}
+ );
+ }
+
+ fetch("https://example.com/example.txt").then(() => {
+ browser.test.pass("Fetch succeeded.");
+ }, () => {
+ browser.test.fail("fetch recieved");
+ browser.test.sendMessage("done");
+ });
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("done");
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html
new file mode 100644
index 000000000..ef77fee3b
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html
@@ -0,0 +1,327 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <script type="text/javascript" src="head_webrequest.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+<script>
+"use strict";
+
+let extension;
+add_task(function* setup() {
+ // SelfSupport has a tendency to fire when running this test alone, without
+ // a good way to turn it off we just set the url to ""
+ yield SpecialPowers.pushPrefEnv({
+ set: [["browser.selfsupport.url", ""]],
+ });
+
+ // Clear the image cache, since it gets in the way otherwise.
+ let imgTools = SpecialPowers.Cc["@mozilla.org/image/tools;1"].getService(SpecialPowers.Ci.imgITools);
+ let cache = imgTools.getImgCacheForDocument(document);
+ cache.clearCache(false);
+
+ extension = makeExtension();
+ yield extension.startup();
+});
+
+// expect is a set of test values used by the background script.
+//
+// type: type of request action
+// events: optional, If defined only the events listed are expected for the
+// request. If undefined, all events except onErrorOccurred
+// and onBeforeRedirect are expected. Must be in order received.
+// redirect: url to redirect to during onBeforeSendHeaders
+// status: number expected status during onHeadersReceived, 200 default
+// cancel: event in which we return cancel=true. cancelled message is sent.
+// cached: expected fromCache value, default is false, checked in onCompletion
+// headers: request or response headers to modify
+
+add_task(function* test_webRequest_links() {
+ let expect = {
+ "file_style_bad.css": {
+ type: "stylesheet",
+ events: ["onBeforeRequest", "onErrorOccurred"],
+ cancel: "onBeforeRequest",
+ },
+ "file_style_redirect.css": {
+ type: "stylesheet",
+ events: ["onBeforeRequest", "onBeforeSendHeaders", "onBeforeRedirect"],
+ optional_events: ["onHeadersReceived"],
+ redirect: "file_style_good.css",
+ },
+ "file_style_good.css": {
+ type: "stylesheet",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addStylesheet("file_style_bad.css");
+ yield extension.awaitMessage("cancelled");
+ // we redirect to style_good which completes the test
+ addStylesheet("file_style_redirect.css");
+ yield extension.awaitMessage("done");
+
+ let style = window.getComputedStyle(document.getElementById("test"), null);
+ is(style.getPropertyValue("color"), "rgb(255, 0, 0)", "Good CSS loaded");
+});
+
+add_task(function* test_webRequest_images() {
+ let expect = {
+ "file_image_bad.png": {
+ type: "image",
+ events: ["onBeforeRequest", "onErrorOccurred"],
+ cancel: "onBeforeRequest",
+ },
+ "file_image_redirect.png": {
+ type: "image",
+ events: ["onBeforeRequest", "onBeforeSendHeaders", "onBeforeRedirect"],
+ optional_events: ["onHeadersReceived"],
+ redirect: "file_image_good.png",
+ },
+ "file_image_good.png": {
+ type: "image",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addImage("file_image_bad.png");
+ yield extension.awaitMessage("cancelled");
+ // we redirect to image_good which completes the test
+ addImage("file_image_redirect.png");
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* test_webRequest_scripts() {
+ let expect = {
+ "file_script_bad.js": {
+ type: "script",
+ events: ["onBeforeRequest", "onErrorOccurred"],
+ cancel: "onBeforeRequest",
+ },
+ "file_script_redirect.js": {
+ type: "script",
+ events: ["onBeforeRequest", "onBeforeSendHeaders", "onBeforeRedirect"],
+ optional_events: ["onHeadersReceived"],
+ redirect: "file_script_good.js",
+ },
+ "file_script_good.js": {
+ type: "script",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addScript("file_script_bad.js");
+ yield extension.awaitMessage("cancelled");
+ // we redirect to script_good which completes the test
+ addScript("file_script_redirect.js");
+ yield extension.awaitMessage("done");
+
+ is(window.success, 1, "Good script ran");
+ is(window.failure, undefined, "Failure script didn't run");
+});
+
+add_task(function* test_webRequest_xhr_get() {
+ let expect = {
+ "file_script_xhr.js": {
+ type: "script",
+ },
+ "xhr_resource": {
+ status: 404,
+ type: "xmlhttprequest",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addScript("file_script_xhr.js");
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* test_webRequest_nonexistent() {
+ let expect = {
+ "nonexistent_script_url.js": {
+ status: 404,
+ type: "script",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addScript("nonexistent_script_url.js");
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* test_webRequest_checkCached() {
+ let expect = {
+ "file_image_good.png": {
+ type: "image",
+ cached: true,
+ },
+ "file_script_good.js": {
+ type: "script",
+ cached: true,
+ },
+ "file_style_good.css": {
+ type: "stylesheet",
+ cached: true,
+ },
+ "nonexistent_script_url.js": {
+ status: 404,
+ type: "script",
+ cached: false,
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addImage("file_image_good.png");
+ addScript("file_script_good.js");
+ addStylesheet("file_style_good.css");
+ addScript("nonexistent_script_url.js");
+ yield extension.awaitMessage("done");
+
+ is(window.success, 2, "Good script ran");
+ is(window.failure, undefined, "Failure script didn't run");
+});
+
+add_task(function* test_webRequest_headers() {
+ let expect = {
+ "file_script_nonexistent.js": {
+ type: "script",
+ status: 404,
+ headers: {
+ request: {
+ add: {
+ "X-WebRequest-request": "text",
+ "X-WebRequest-request-binary": "binary",
+ },
+ modify: {
+ "user-agent": "WebRequest",
+ },
+ remove: [
+ "referer",
+ ],
+ },
+ response: {
+ add: {
+ "X-WebRequest-response": "text",
+ "X-WebRequest-response-binary": "binary",
+ },
+ modify: {
+ "server": "WebRequest",
+ "content-type": "text/html; charset=utf-8",
+ },
+ remove: [
+ "connection",
+ ],
+ },
+ },
+ completion: "onCompleted",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addScript("file_script_nonexistent.js");
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* test_webRequest_tabId() {
+ let expect = {
+ "file_WebRequest_page3.html": {
+ type: "main_frame",
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ let a = addLink("file_WebRequest_page3.html?trigger=a");
+ a.click();
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* test_webRequest_tabId_browser() {
+ async function background(url) {
+ let tabId;
+ browser.test.onMessage.addListener(async (msg, expected) => {
+ await browser.tabs.remove(tabId);
+ browser.test.sendMessage("done");
+ });
+
+ let tab = await browser.tabs.create({url});
+ tabId = tab.id;
+ }
+
+ let tabExt = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "tabs",
+ ],
+ },
+ background: `(${background})('${SimpleTest.getTestFileURL("file_sample.html")}?nocache=${Math.random()}')`,
+ });
+
+ let expect = {
+ "file_sample.html": {
+ type: "main_frame",
+ },
+ };
+ // expecting origin == undefined
+ extension.sendMessage("set-expected", {expect});
+ yield extension.awaitMessage("continue");
+
+ // open a tab from a system principal
+ yield tabExt.startup();
+
+ yield extension.awaitMessage("done");
+ tabExt.sendMessage("done");
+ yield tabExt.awaitMessage("done");
+ yield tabExt.unload();
+});
+
+add_task(function* test_webRequest_frames() {
+ let expect = {
+ "text/plain,webRequestTest": {
+ type: "sub_frame",
+ events: ["onBeforeRequest", "onCompleted"],
+ },
+ "text/plain,webRequestTest_bad": {
+ type: "sub_frame",
+ events: ["onBeforeRequest", "onCompleted"],
+ cancel: "onBeforeRequest",
+ },
+ "redirection.sjs": {
+ status: 302,
+ type: "sub_frame",
+ events: ["onBeforeRequest", "onBeforeSendHeaders", "onSendHeaders", "onHeadersReceived", "onBeforeRedirect"],
+ },
+ "dummy_page.html": {
+ type: "sub_frame",
+ status: 404,
+ },
+ "badrobot": {
+ type: "sub_frame",
+ status: 404,
+ events: ["onBeforeRequest", "onBeforeSendHeaders", "onSendHeaders", "onErrorOccurred"],
+ },
+ };
+ extension.sendMessage("set-expected", {expect, origin: location.href});
+ yield extension.awaitMessage("continue");
+ addFrame("data:text/plain,webRequestTest");
+ addFrame("data:text/plain,webRequestTest_bad");
+ yield extension.awaitMessage("cancelled");
+ addFrame("redirection.sjs");
+ addFrame("https://invalid.localhost/badrobot");
+ yield extension.awaitMessage("done");
+});
+
+add_task(function* teardown() {
+ yield extension.unload();
+});
+</script>
+</head>
+<body>
+<div id="test">Sample text</div>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html
new file mode 100644
index 000000000..c8423ec7c
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html
@@ -0,0 +1,216 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for simple WebExtension</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_suspend() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "webRequestBlocking",
+ ],
+ },
+
+ background() {
+ browser.webRequest.onBeforeSendHeaders.addListener(
+ details => {
+ // Make sure that returning undefined or a promise that resolves to
+ // undefined does not break later handlers.
+ },
+ {urls: ["<all_urls>"]},
+ ["blocking", "requestHeaders"]);
+
+ browser.webRequest.onBeforeSendHeaders.addListener(
+ details => {
+ return Promise.resolve();
+ },
+ {urls: ["<all_urls>"]},
+ ["blocking", "requestHeaders"]);
+
+ browser.webRequest.onBeforeSendHeaders.addListener(
+ details => {
+ let requestHeaders = details.requestHeaders.concat({name: "Foo", value: "Bar"});
+
+ return new Promise(resolve => {
+ setTimeout(resolve, 500);
+ }).then(() => {
+ return {requestHeaders};
+ });
+ },
+ {urls: ["<all_urls>"]},
+ ["blocking", "requestHeaders"]);
+ },
+ });
+
+ yield extension.startup();
+
+ let result = yield fetch(SimpleTest.getTestFileURL("return_headers.sjs"));
+
+ let headers = JSON.parse(yield result.text());
+
+ is(headers.foo, "Bar", "Request header was correctly set on suspended request");
+
+ yield extension.unload();
+});
+
+
+// Test that requests that were canceled while suspended for a blocking
+// listener are correctly resumed.
+add_task(function* test_error_resume() {
+ let chromeScript = SpecialPowers.loadChromeScript(() => {
+ const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+ Cu.import("resource://gre/modules/Services.jsm");
+
+ let observer = channel => {
+ if (channel instanceof Ci.nsIHttpChannel && channel.URI.spec === "http://example.com/") {
+ Services.obs.removeObserver(observer, "http-on-modify-request");
+
+ // Wait until the next tick to make sure this runs after WebRequest observers.
+ Promise.resolve().then(() => {
+ channel.cancel(Cr.NS_BINDING_ABORTED);
+ });
+ }
+ };
+
+ Services.obs.addObserver(observer, "http-on-modify-request", false);
+ });
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "webRequestBlocking",
+ ],
+ },
+
+ background() {
+ browser.webRequest.onBeforeSendHeaders.addListener(
+ details => {
+ browser.test.log(`onBeforeSendHeaders({url: ${details.url}})`);
+
+ if (details.url === "http://example.com/") {
+ browser.test.sendMessage("got-before-send-headers");
+ }
+ },
+ {urls: ["<all_urls>"]},
+ ["blocking"]);
+
+ browser.webRequest.onErrorOccurred.addListener(
+ details => {
+ browser.test.log(`onErrorOccurred({url: ${details.url}})`);
+
+ if (details.url === "http://example.com/") {
+ browser.test.sendMessage("got-error-occurred");
+ }
+ },
+ {urls: ["<all_urls>"]});
+ },
+ });
+
+ yield extension.startup();
+
+ try {
+ yield fetch("http://example.com/");
+ ok(false, "Fetch should have failed.");
+ } catch (e) {
+ ok(true, "Got expected error.");
+ }
+
+ yield extension.awaitMessage("got-before-send-headers");
+ yield extension.awaitMessage("got-error-occurred");
+
+ yield extension.unload();
+ chromeScript.destroy();
+});
+
+
+// Test that response header modifications take effect before onStartRequest fires.
+add_task(function* test_set_responseHeaders() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "webRequestBlocking",
+ "http://example.com/",
+ ],
+ },
+
+ background() {
+ browser.webRequest.onHeadersReceived.addListener(
+ details => {
+ browser.test.log(`onHeadersReceived({url: ${details.url}})`);
+
+ details.responseHeaders.push({name: "foo", value: "bar"});
+
+ return {responseHeaders: details.responseHeaders};
+ },
+ {urls: ["http://example.com/?modify_headers"]},
+ ["blocking", "responseHeaders"]);
+ },
+ });
+
+ yield extension.startup();
+
+ yield new Promise(resolve => setTimeout(resolve, 0));
+
+ let chromeScript = SpecialPowers.loadChromeScript(() => {
+ const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+ Cu.import("resource://gre/modules/NetUtil.jsm");
+ Cu.import("resource://gre/modules/Services.jsm");
+ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+ let ssm = Services.scriptSecurityManager;
+
+ let channel = NetUtil.newChannel({
+ uri: "http://example.com/?modify_headers",
+ loadingPrincipal: ssm.createCodebasePrincipalFromOrigin("http://example.com"),
+ contentPolicyType: Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST,
+ securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
+ });
+
+ channel.asyncOpen2({
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener]),
+
+ onStartRequest(request, context) {
+ request.QueryInterface(Ci.nsIHttpChannel);
+
+ try {
+ sendAsyncMessage("response-header-foo", request.getResponseHeader("foo"));
+ } catch (e) {
+ sendAsyncMessage("response-header-foo", null);
+ }
+ request.cancel(Cr.NS_BINDING_ABORTED);
+ },
+
+ onStopRequest() {
+ },
+
+ onDataAvailable() {
+ throw new Components.Exception("", Cr.NS_ERROR_FAILURE);
+ },
+ });
+ });
+
+ let headerValue = yield chromeScript.promiseOneMessage("response-header-foo");
+ is(headerValue, "bar", "Expected Foo header value");
+
+ yield extension.unload();
+ chromeScript.destroy();
+});
+
+
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html
new file mode 100644
index 000000000..998ab9800
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html
@@ -0,0 +1,199 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<form method="post"
+ action="file_WebRequest_page3.html?trigger=form"
+ target="_blank"
+ enctype="multipart/form-data"
+ >
+<input type="text" name="&quot;special&quot; chˆrs" value="spÛcial">
+<input type="file" name="testFile">
+<input type="file" name="emptyFile">
+<input type="text" name="textInput1" value="value1">
+</form>
+
+<form method="post"
+ action="file_WebRequest_page3.html?trigger=form"
+ target="_blank"
+ enctype="multipart/form-data"
+ >
+<input type="text" name="textInput2" value="value2">
+<input type="file" name="testFile">
+<input type="file" name="emptyFile">
+</form>
+
+</form>
+<form method="post"
+ action="file_WebRequest_page3.html?trigger=form"
+ target="_blank"
+ >
+<input type="text" name="textInput" value="value1">
+<input type="text" name="textInput" value="value2">
+</form>
+<script>
+"use strict";
+
+let files, testFile, blob, file, uploads;
+add_task(function* test_setup() {
+ files = yield new Promise(resolve => {
+ SpecialPowers.createFiles([{name: "testFile.pdf", data: "Not really a PDF file :)", "type": "application/x-pdf"}], (result) => {
+ resolve(result);
+ });
+ });
+ testFile = files[0];
+ blob = {
+ name: "blobAsFile",
+ content: new Blob(["A blob sent as a file"], {type: "text/csv"}),
+ fileName: "blobAsFile.csv",
+ };
+ file = {
+ name: "testFile",
+ fileName: testFile.name,
+ };
+ uploads = {
+ [blob.name]: blob,
+ [file.name]: file,
+ };
+});
+
+function background() {
+ const FILTERS = {urls: ["<all_urls>"]};
+
+ let requestBodySupported = true;
+
+ function onUpload(details) {
+ let url = new URL(details.url);
+ let upload = url.searchParams.get("upload");
+ if (!upload || !requestBodySupported) {
+ return;
+ }
+ let requestBody = details.requestBody;
+ browser.test.log(`onBeforeRequest upload: ${details.url} ${JSON.stringify(details.requestBody)}`);
+ browser.test.assertTrue(!!requestBody, `Intercepted upload ${details.url} #${details.requestId} ${upload} have a requestBody`);
+ if (!requestBody) {
+ return;
+ }
+ let byteLength = parseInt(upload, 10);
+ if (byteLength) {
+ browser.test.assertTrue(!!requestBody.raw, `Binary upload ${details.url} #${details.requestId} ${upload} have a raw attribute`);
+ browser.test.assertEq(byteLength, requestBody.raw && requestBody.raw.map(r => r.bytes && r.bytes.byteLength || 0).reduce((a, b) => a + b), `Binary upload size matches`);
+ return;
+ }
+ if ("raw" in requestBody) {
+ browser.test.assertEq(upload, JSON.stringify(requestBody.raw).replace(/(\bfile: ")[^"]+/, "$1<file>"), `Upload ${details.url} #${details.requestId} matches raw data`);
+ } else {
+ browser.test.assertEq(upload, JSON.stringify(requestBody.formData), `Upload ${details.url} #${details.requestId} matches form data.`);
+ }
+ }
+
+ browser.webRequest.onCompleted.addListener(
+ details => {
+ browser.test.log(`onCompleted ${details.requestId} ${details.url}`);
+
+ browser.test.sendMessage("done");
+ },
+ FILTERS);
+
+ let onBeforeRequest = details => {
+ browser.test.log(`${name} ${details.requestId} ${details.url}`);
+
+ onUpload(details);
+ };
+
+ try {
+ browser.webRequest.onBeforeRequest.addListener(
+ onBeforeRequest, FILTERS, ["requestBody"]);
+ } catch (e) {
+ browser.test.assertTrue(/\brequestBody\b/.test(e.message),
+ "Request body is unsupported");
+
+ // requestBody is disabled in release builds
+ if (!/\brequestBody\b/.test(e.message)) {
+ throw e;
+ }
+
+ browser.webRequest.onBeforeRequest.addListener(
+ onBeforeRequest, FILTERS);
+ }
+}
+
+add_task(function* test_xhr_forms() {
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: [
+ "webRequest",
+ "webRequestBlocking",
+ "<all_urls>",
+ ],
+ },
+ background,
+ });
+
+ yield extension.startup();
+
+ for (let form of document.forms) {
+ if (file.name in form.elements) {
+ SpecialPowers.wrap(form.elements[file.name]).mozSetFileArray(files);
+ }
+ let action = new URL(form.action);
+ let formData = new FormData(form);
+ let webRequestFD = {};
+
+ let updateActionURL = () => {
+ for (let name of formData.keys()) {
+ webRequestFD[name] = name in uploads ? [uploads[name].fileName] : formData.getAll(name);
+ }
+ action.searchParams.set("upload", JSON.stringify(webRequestFD));
+ action.searchParams.set("enctype", form.enctype);
+ };
+
+ updateActionURL();
+
+ form.action = action;
+ form.submit();
+ yield extension.awaitMessage("done");
+
+ if (form.enctype !== "multipart/form-data") {
+ continue;
+ }
+
+ let post = (data) => {
+ let xhr = new XMLHttpRequest();
+ action.searchParams.set("xhr", "1");
+ xhr.open("POST", action.href);
+ xhr.send(data);
+ action.searchParams.delete("xhr");
+ return extension.awaitMessage("done");
+ };
+
+ formData.append(blob.name, blob.content, blob.fileName);
+ formData.append("formDataField", "some value");
+ updateActionURL();
+ yield post(formData);
+
+ action.searchParams.set("upload", JSON.stringify([{file: "<file>"}]));
+ yield post(testFile);
+
+ action.searchParams.set("upload", `${blob.content.size} bytes`);
+ yield post(blob.content);
+
+ let byteLength = 16;
+ action.searchParams.set("upload", `${byteLength} bytes`);
+ yield post(new ArrayBuffer(byteLength));
+ }
+
+ yield extension.unload();
+});
+</script>
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html b/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html
new file mode 100644
index 000000000..7d49d55ba
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html
@@ -0,0 +1,105 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test for content script</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* test_postMessage() {
+ let extensionData = {
+ manifest: {
+ content_scripts: [
+ {
+ "matches": ["http://mochi.test/*/file_sample.html"],
+ "js": ["content_script.js"],
+ "run_at": "document_start",
+ "all_frames": true,
+ },
+ ],
+
+ web_accessible_resources: ["iframe.html"],
+ },
+
+ background() {
+ browser.test.sendMessage("iframe-url", browser.runtime.getURL("iframe.html"));
+ },
+
+ files: {
+ "content_script.js": function() {
+ window.addEventListener("message", event => {
+ if (event.data == "ping") {
+ event.source.postMessage({pong: location.href},
+ event.origin);
+ }
+ });
+ },
+
+ "iframe.html": `<!DOCTYPE html>
+ <html>
+ <head>
+ <meta charset="utf-8">
+ <script src="content_script.js"><\/script>
+ </head>
+ </html>`,
+ },
+ };
+
+ let createIframe = url => {
+ let iframe = document.createElement("iframe");
+ return new Promise(resolve => {
+ iframe.src = url;
+ iframe.onload = resolve;
+ document.body.appendChild(iframe);
+ }).then(() => {
+ return iframe;
+ });
+ };
+
+ let awaitMessage = () => {
+ return new Promise(resolve => {
+ let listener = event => {
+ if (event.data.pong) {
+ window.removeEventListener("message", listener);
+ resolve(event.data);
+ }
+ };
+ window.addEventListener("message", listener);
+ });
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ let iframeURL = yield extension.awaitMessage("iframe-url");
+ let testURL = SimpleTest.getTestFileURL("file_sample.html");
+
+ for (let url of [iframeURL, testURL]) {
+ info(`Testing URL ${url}`);
+
+ let iframe = yield createIframe(url);
+
+ iframe.contentWindow.postMessage(
+ "ping", url);
+
+ let pong = yield awaitMessage();
+ is(pong.pong, url, "Got expected pong");
+
+ iframe.remove();
+ }
+
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html b/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html
new file mode 100644
index 000000000..1afdadb9f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html
@@ -0,0 +1,86 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Test XHR capabilities</title>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
+ <script type="text/javascript" src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+
+<script type="text/javascript">
+"use strict";
+
+add_task(function* test_xhr_capabilities() {
+ function backgroundScript() {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", browser.extension.getURL("bad.xml"));
+
+ browser.test.sendMessage("result",
+ {name: "Background script XHRs should not be privileged",
+ result: xhr.channel === undefined});
+
+ xhr.onload = () => {
+ browser.test.sendMessage("result",
+ {name: "Background script XHRs should not yield <parsererrors>",
+ result: xhr.responseXML === null});
+ };
+ xhr.send();
+ }
+
+ function contentScript() {
+ let xhr = new XMLHttpRequest();
+ xhr.open("GET", browser.extension.getURL("bad.xml"));
+
+ browser.test.sendMessage("result",
+ {name: "Content script XHRs should not be privileged",
+ result: xhr.channel === undefined});
+
+ xhr.onload = () => {
+ browser.test.sendMessage("result",
+ {name: "Content script XHRs should not yield <parsererrors>",
+ result: xhr.responseXML === null});
+ };
+ xhr.send();
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ background: {
+ "scripts": ["background.js"],
+ },
+ content_scripts: [{
+ "matches": ["http://example.com/"],
+ "js": ["content_script.js"],
+ }],
+ web_accessible_resources: [
+ "bad.xml",
+ ],
+ },
+
+ files: {
+ "bad.xml": "<xml",
+ "background.js": `(${backgroundScript})()`,
+ "content_script.js": `(${contentScript})()`,
+ },
+ });
+
+ yield extension.startup();
+
+ let win = window.open("http://example.com/");
+
+ // We expect four test results from the content/background scripts.
+ for (let i = 0; i < 4; ++i) {
+ let result = yield extension.awaitMessage("result");
+ ok(result.result, result.name);
+ }
+
+ win.close();
+ yield extension.unload();
+});
+</script>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js b/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js
new file mode 100644
index 000000000..ccfb2ac1f
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js
@@ -0,0 +1,8 @@
+"use strict";
+
+onmessage = function(event) {
+ fetch("https://example.com/example.txt").then(() => {
+ postMessage("Done!");
+ });
+};
+
diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm b/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm
new file mode 100644
index 000000000..bfb148301
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm
@@ -0,0 +1,22 @@
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["webrequest_test"];
+
+Components.utils.importGlobalProperties(["fetch", "XMLHttpRequest"]);
+
+this.webrequest_test = {
+ testFetch(url) {
+ return fetch(url);
+ },
+
+ testXHR(url) {
+ return new Promise(resolve => {
+ let xhr = new XMLHttpRequest();
+ xhr.open("HEAD", url);
+ xhr.onload = () => {
+ resolve();
+ };
+ xhr.send();
+ });
+ },
+};
diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_worker.js b/toolkit/components/webextensions/test/mochitest/webrequest_worker.js
new file mode 100644
index 000000000..dcffd0857
--- /dev/null
+++ b/toolkit/components/webextensions/test/mochitest/webrequest_worker.js
@@ -0,0 +1,3 @@
+"use strict";
+
+fetch("https://example.com/example.txt");
diff --git a/toolkit/components/webextensions/test/xpcshell/.eslintrc.js b/toolkit/components/webextensions/test/xpcshell/.eslintrc.js
new file mode 100644
index 000000000..3758537ef
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/.eslintrc.js
@@ -0,0 +1,9 @@
+"use strict";
+
+module.exports = { // eslint-disable-line no-undef
+ "extends": "../../../../../testing/xpcshell/xpcshell.eslintrc.js",
+
+ "globals": {
+ "browser": false,
+ },
+};
diff --git a/toolkit/components/webextensions/test/xpcshell/data/file_download.html b/toolkit/components/webextensions/test/xpcshell/data/file_download.html
new file mode 100644
index 000000000..d970c6325
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/data/file_download.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+
+<html>
+<head>
+<meta charset="utf-8">
+</head>
+<body>
+
+<div>Download HTML File</div>
+
+</body>
+</html>
diff --git a/toolkit/components/webextensions/test/xpcshell/data/file_download.txt b/toolkit/components/webextensions/test/xpcshell/data/file_download.txt
new file mode 100644
index 000000000..6293c7af7
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/data/file_download.txt
@@ -0,0 +1 @@
+This is a sample file used in download tests.
diff --git a/toolkit/components/webextensions/test/xpcshell/head.js b/toolkit/components/webextensions/test/xpcshell/head.js
new file mode 100644
index 000000000..9e22be6da
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/head.js
@@ -0,0 +1,111 @@
+"use strict";
+
+const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
+
+/* exported createHttpServer, promiseConsoleOutput, cleanupDir */
+
+Components.utils.import("resource://gre/modules/Task.jsm");
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
+Components.utils.import("resource://gre/modules/Timer.jsm");
+Components.utils.import("resource://testing-common/AddonTestUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Extension",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionData",
+ "resource://gre/modules/Extension.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement",
+ "resource://gre/modules/ExtensionManagement.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestUtils",
+ "resource://testing-common/ExtensionXPCShellUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
+ "resource://gre/modules/FileUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "HttpServer",
+ "resource://testing-common/httpd.js");
+XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
+ "resource://gre/modules/NetUtil.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Schemas",
+ "resource://gre/modules/Schemas.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+
+ExtensionTestUtils.init(this);
+
+/**
+ * Creates a new HttpServer for testing, and begins listening on the
+ * specified port. Automatically shuts down the server when the test
+ * unit ends.
+ *
+ * @param {integer} [port]
+ * The port to listen on. If omitted, listen on a random
+ * port. The latter is the preferred behavior.
+ *
+ * @returns {HttpServer}
+ */
+function createHttpServer(port = -1) {
+ let server = new HttpServer();
+ server.start(port);
+
+ do_register_cleanup(() => {
+ return new Promise(resolve => {
+ server.stop(resolve);
+ });
+ });
+
+ return server;
+}
+
+var promiseConsoleOutput = Task.async(function* (task) {
+ const DONE = `=== console listener ${Math.random()} done ===`;
+
+ let listener;
+ let messages = [];
+ let awaitListener = new Promise(resolve => {
+ listener = msg => {
+ if (msg == DONE) {
+ resolve();
+ } else {
+ void (msg instanceof Ci.nsIConsoleMessage);
+ messages.push(msg);
+ }
+ };
+ });
+
+ Services.console.registerListener(listener);
+ try {
+ let result = yield task();
+
+ Services.console.logStringMessage(DONE);
+ yield awaitListener;
+
+ return {messages, result};
+ } finally {
+ Services.console.unregisterListener(listener);
+ }
+});
+
+// Attempt to remove a directory. If the Windows OS is still using the
+// file sometimes remove() will fail. So try repeatedly until we can
+// remove it or we give up.
+function cleanupDir(dir) {
+ let count = 0;
+ return new Promise((resolve, reject) => {
+ function tryToRemoveDir() {
+ count += 1;
+ try {
+ dir.remove(true);
+ } catch (e) {
+ // ignore
+ }
+ if (!dir.exists()) {
+ return resolve();
+ }
+ if (count >= 25) {
+ return reject(`Failed to cleanup directory: ${dir}`);
+ }
+ setTimeout(tryToRemoveDir, 100);
+ }
+ tryToRemoveDir();
+ });
+}
diff --git a/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js
new file mode 100644
index 000000000..f7c619b76
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js
@@ -0,0 +1,131 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* globals AppConstants, FileUtils */
+/* exported getSubprocessCount, setupHosts, waitForSubprocessExit */
+
+XPCOMUtils.defineLazyModuleGetter(this, "MockRegistry",
+ "resource://testing-common/MockRegistry.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
+ "resource://gre/modules/Timer.jsm");
+
+let {Subprocess, SubprocessImpl} = Cu.import("resource://gre/modules/Subprocess.jsm");
+
+
+// It's important that we use a space in this directory name to make sure we
+// correctly handle executing batch files with spaces in their path.
+let tmpDir = FileUtils.getDir("TmpD", ["Native Messaging"]);
+tmpDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+do_register_cleanup(() => {
+ tmpDir.remove(true);
+});
+
+function getPath(filename) {
+ return OS.Path.join(tmpDir.path, filename);
+}
+
+const ID = "native@tests.mozilla.org";
+
+
+function* setupHosts(scripts) {
+ const PERMS = {unixMode: 0o755};
+
+ const env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment);
+ const pythonPath = yield Subprocess.pathSearch(env.get("PYTHON"));
+
+ function* writeManifest(script, scriptPath, path) {
+ let body = `#!${pythonPath} -u\n${script.script}`;
+
+ yield OS.File.writeAtomic(scriptPath, body);
+ yield OS.File.setPermissions(scriptPath, PERMS);
+
+ let manifest = {
+ name: script.name,
+ description: script.description,
+ path,
+ type: "stdio",
+ allowed_extensions: [ID],
+ };
+
+ let manifestPath = getPath(`${script.name}.json`);
+ yield OS.File.writeAtomic(manifestPath, JSON.stringify(manifest));
+
+ return manifestPath;
+ }
+
+ switch (AppConstants.platform) {
+ case "macosx":
+ case "linux":
+ let dirProvider = {
+ getFile(property) {
+ if (property == "XREUserNativeMessaging") {
+ return tmpDir.clone();
+ } else if (property == "XRESysNativeMessaging") {
+ return tmpDir.clone();
+ }
+ return null;
+ },
+ };
+
+ Services.dirsvc.registerProvider(dirProvider);
+ do_register_cleanup(() => {
+ Services.dirsvc.unregisterProvider(dirProvider);
+ });
+
+ for (let script of scripts) {
+ let path = getPath(`${script.name}.py`);
+
+ yield writeManifest(script, path, path);
+ }
+ break;
+
+ case "win":
+ const REGKEY = String.raw`Software\Mozilla\NativeMessagingHosts`;
+
+ let registry = new MockRegistry();
+ do_register_cleanup(() => {
+ registry.shutdown();
+ });
+
+ for (let script of scripts) {
+ // It's important that we use a space in this filename. See directory
+ // name comment above.
+ let batPath = getPath(`batch ${script.name}.bat`);
+ let scriptPath = getPath(`${script.name}.py`);
+
+ let batBody = `@ECHO OFF\n${pythonPath} -u "${scriptPath}" %*\n`;
+ yield OS.File.writeAtomic(batPath, batBody);
+
+ // Create absolute and relative path versions of the entry.
+ for (let [name, path] of [[script.name, batPath],
+ [`relative.${script.name}`, OS.Path.basename(batPath)]]) {
+ script.name = name;
+ let manifestPath = yield writeManifest(script, scriptPath, path);
+
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
+ `${REGKEY}\\${script.name}`, "", manifestPath);
+ }
+ }
+ break;
+
+ default:
+ ok(false, `Native messaging is not supported on ${AppConstants.platform}`);
+ }
+}
+
+
+function getSubprocessCount() {
+ return SubprocessImpl.Process.getWorker().call("getProcesses", [])
+ .then(result => result.size);
+}
+function waitForSubprocessExit() {
+ return SubprocessImpl.Process.getWorker().call("waitForNoProcesses", []).then(() => {
+ // Return to the main event loop to give IO handlers enough time to consume
+ // their remaining buffered input.
+ return new Promise(resolve => setTimeout(resolve, 0));
+ });
+}
diff --git a/toolkit/components/webextensions/test/xpcshell/head_sync.js b/toolkit/components/webextensions/test/xpcshell/head_sync.js
new file mode 100644
index 000000000..9b66b78e7
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/head_sync.js
@@ -0,0 +1,67 @@
+/* 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";
+
+/* exported withSyncContext */
+
+Components.utils.import("resource://gre/modules/Services.jsm", this);
+Components.utils.import("resource://gre/modules/ExtensionCommon.jsm", this);
+
+var {
+ BaseContext,
+} = ExtensionCommon;
+
+class Context extends BaseContext {
+ constructor(principal) {
+ super();
+ Object.defineProperty(this, "principal", {
+ value: principal,
+ configurable: true,
+ });
+ this.sandbox = Components.utils.Sandbox(principal, {wantXrays: false});
+ this.extension = {id: "test@web.extension"};
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+}
+
+/**
+ * Call the given function with a newly-constructed context.
+ * Unload the context on the way out.
+ *
+ * @param {function} f the function to call
+ */
+function* withContext(f) {
+ const ssm = Services.scriptSecurityManager;
+ const PRINCIPAL1 = ssm.createCodebasePrincipalFromOrigin("http://www.example.org");
+ const context = new Context(PRINCIPAL1);
+ try {
+ yield* f(context);
+ } finally {
+ yield context.unload();
+ }
+}
+
+/**
+ * Like withContext(), but also turn on the "storage.sync" pref for
+ * the duration of the function.
+ * Calls to this function can be replaced with calls to withContext
+ * once the pref becomes on by default.
+ *
+ * @param {function} f the function to call
+ */
+function* withSyncContext(f) {
+ const STORAGE_SYNC_PREF = "webextensions.storage.sync.enabled";
+ let prefs = Services.prefs;
+
+ try {
+ prefs.setBoolPref(STORAGE_SYNC_PREF, true);
+ yield* withContext(f);
+ } finally {
+ prefs.clearUserPref(STORAGE_SYNC_PREF);
+ }
+}
diff --git a/toolkit/components/webextensions/test/xpcshell/native_messaging.ini b/toolkit/components/webextensions/test/xpcshell/native_messaging.ini
new file mode 100644
index 000000000..d0e1da163
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/native_messaging.ini
@@ -0,0 +1,13 @@
+[DEFAULT]
+head = head.js head_native_messaging.js
+tail =
+firefox-appdir = browser
+skip-if = appname == "thunderbird" || os == "android"
+subprocess = true
+support-files =
+ data/**
+tags = webextensions
+
+[test_ext_native_messaging.js]
+[test_ext_native_messaging_perf.js]
+[test_ext_native_messaging_unresponsive.js]
diff --git a/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js b/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js
new file mode 100644
index 000000000..b6213baac
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js
@@ -0,0 +1,38 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://gre/modules/Preferences.jsm");
+
+const ADDON_ID = "test@web.extension";
+
+const aps = Cc["@mozilla.org/addons/policy-service;1"]
+ .getService(Ci.nsIAddonPolicyService).wrappedJSObject;
+
+do_register_cleanup(() => {
+ aps.setAddonCSP(ADDON_ID, null);
+});
+
+add_task(function* test_addon_csp() {
+ equal(aps.baseCSP, Preferences.get("extensions.webextensions.base-content-security-policy"),
+ "Expected base CSP value");
+
+ equal(aps.defaultCSP, Preferences.get("extensions.webextensions.default-content-security-policy"),
+ "Expected default CSP value");
+
+ equal(aps.getAddonCSP(ADDON_ID), aps.defaultCSP,
+ "CSP for unknown add-on ID should be the default CSP");
+
+
+ const CUSTOM_POLICY = "script-src: 'self' https://xpcshell.test.custom.csp; object-src: 'none'";
+
+ aps.setAddonCSP(ADDON_ID, CUSTOM_POLICY);
+
+ equal(aps.getAddonCSP(ADDON_ID), CUSTOM_POLICY, "CSP should point to add-on's custom policy");
+
+
+ aps.setAddonCSP(ADDON_ID, null);
+
+ equal(aps.getAddonCSP(ADDON_ID), aps.defaultCSP,
+ "CSP should revert to default when set to null");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js b/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js
new file mode 100644
index 000000000..59a7322bc
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js
@@ -0,0 +1,85 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+const cps = Cc["@mozilla.org/addons/content-policy;1"].getService(Ci.nsIAddonContentPolicy);
+
+add_task(function* test_csp_validator() {
+ let checkPolicy = (policy, expectedResult, message = null) => {
+ do_print(`Checking policy: ${policy}`);
+
+ let result = cps.validateAddonCSP(policy);
+ equal(result, expectedResult);
+ };
+
+ checkPolicy("script-src 'self'; object-src 'self';",
+ null);
+
+ let hash = "'sha256-NjZhMDQ1YjQ1MjEwMmM1OWQ4NDBlYzA5N2Q1OWQ5NDY3ZTEzYTNmMzRmNjQ5NGU1MzlmZmQzMmMxYmIzNWYxOCAgLQo='";
+
+ checkPolicy(`script-src 'self' https://com https://*.example.com moz-extension://09abcdef blob: filesystem: ${hash} 'unsafe-eval'; ` +
+ `object-src 'self' https://com https://*.example.com moz-extension://09abcdef blob: filesystem: ${hash}`,
+ null);
+
+ checkPolicy("",
+ "Policy is missing a required \u2018script-src\u2019 directive");
+
+ checkPolicy("object-src 'none';",
+ "Policy is missing a required \u2018script-src\u2019 directive");
+
+
+ checkPolicy("default-src 'self'", null,
+ "A valid default-src should count as a valid script-src or object-src");
+
+ checkPolicy("default-src 'self'; script-src 'self'", null,
+ "A valid default-src should count as a valid script-src or object-src");
+
+ checkPolicy("default-src 'self'; object-src 'self'", null,
+ "A valid default-src should count as a valid script-src or object-src");
+
+
+ checkPolicy("default-src 'self'; script-src http://example.com",
+ "\u2018script-src\u2019 directive contains a forbidden http: protocol source",
+ "A valid default-src should not allow an invalid script-src directive");
+
+ checkPolicy("default-src 'self'; object-src http://example.com",
+ "\u2018object-src\u2019 directive contains a forbidden http: protocol source",
+ "A valid default-src should not allow an invalid object-src directive");
+
+
+ checkPolicy("script-src 'self';",
+ "Policy is missing a required \u2018object-src\u2019 directive");
+
+ checkPolicy("script-src 'none'; object-src 'none'",
+ "\u2018script-src\u2019 must include the source 'self'");
+
+ checkPolicy("script-src 'self'; object-src 'none';",
+ null);
+
+ checkPolicy("script-src 'self' 'unsafe-inline'; object-src 'self';",
+ "\u2018script-src\u2019 directive contains a forbidden 'unsafe-inline' keyword");
+
+
+ let directives = ["script-src", "object-src"];
+
+ for (let [directive, other] of [directives, directives.slice().reverse()]) {
+ for (let src of ["https://*", "https://*.blogspot.com", "https://*"]) {
+ checkPolicy(`${directive} 'self' ${src}; ${other} 'self';`,
+ `https: wildcard sources in \u2018${directive}\u2019 directives must include at least one non-generic sub-domain (e.g., *.example.com rather than *.com)`);
+ }
+
+ checkPolicy(`${directive} 'self' https:; ${other} 'self';`,
+ `https: protocol requires a host in \u2018${directive}\u2019 directives`);
+
+ checkPolicy(`${directive} 'self' http://example.com; ${other} 'self';`,
+ `\u2018${directive}\u2019 directive contains a forbidden http: protocol source`);
+
+ for (let protocol of ["http", "ftp", "meh"]) {
+ checkPolicy(`${directive} 'self' ${protocol}:; ${other} 'self';`,
+ `\u2018${directive}\u2019 directive contains a forbidden ${protocol}: protocol source`);
+ }
+
+ checkPolicy(`${directive} 'self' 'nonce-01234'; ${other} 'self';`,
+ `\u2018${directive}\u2019 directive contains a forbidden 'nonce-*' keyword`);
+ }
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js
new file mode 100644
index 000000000..936c984c6
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js
@@ -0,0 +1,210 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_alarm_without_permissions() {
+ function backgroundScript() {
+ browser.test.assertTrue(!browser.alarms,
+ "alarm API is not available when the alarm permission is not required");
+ browser.test.notifyPass("alarms_permission");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: [],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarms_permission");
+ yield extension.unload();
+});
+
+
+add_task(function* test_alarm_fires() {
+ function backgroundScript() {
+ let ALARM_NAME = "test_ext_alarms";
+ let timer;
+
+ browser.alarms.onAlarm.addListener(alarm => {
+ browser.test.assertEq(ALARM_NAME, alarm.name, "alarm has the correct name");
+ clearTimeout(timer);
+ browser.test.notifyPass("alarm-fires");
+ });
+
+ browser.alarms.create(ALARM_NAME, {delayInMinutes: 0.02});
+
+ timer = setTimeout(async () => {
+ browser.test.fail("alarm fired within expected time");
+ let wasCleared = await browser.alarms.clear(ALARM_NAME);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+ browser.test.notifyFail("alarm-fires");
+ }, 10000);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-fires");
+ yield extension.unload();
+});
+
+
+add_task(function* test_alarm_fires_with_when() {
+ function backgroundScript() {
+ let ALARM_NAME = "test_ext_alarms";
+ let timer;
+
+ browser.alarms.onAlarm.addListener(alarm => {
+ browser.test.assertEq(ALARM_NAME, alarm.name, "alarm has the expected name");
+ clearTimeout(timer);
+ browser.test.notifyPass("alarm-when");
+ });
+
+ browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000});
+
+ timer = setTimeout(async () => {
+ browser.test.fail("alarm fired within expected time");
+ let wasCleared = await browser.alarms.clear(ALARM_NAME);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+ browser.test.notifyFail("alarm-when");
+ }, 10000);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-when");
+ yield extension.unload();
+});
+
+
+add_task(function* test_alarm_clear_non_matching_name() {
+ async function backgroundScript() {
+ let ALARM_NAME = "test_ext_alarms";
+
+ browser.alarms.create(ALARM_NAME, {when: Date.now() + 2000});
+
+ let wasCleared = await browser.alarms.clear(ALARM_NAME + "1");
+ browser.test.assertFalse(wasCleared, "alarm was not cleared");
+
+ let alarms = await browser.alarms.getAll();
+ browser.test.assertEq(1, alarms.length, "alarm was not removed");
+ browser.test.notifyPass("alarm-clear");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-clear");
+ yield extension.unload();
+});
+
+
+add_task(function* test_alarm_get_and_clear_single_argument() {
+ async function backgroundScript() {
+ browser.alarms.create({when: Date.now() + 2000});
+
+ let alarm = await browser.alarms.get();
+ browser.test.assertEq("", alarm.name, "expected alarm returned");
+
+ let wasCleared = await browser.alarms.clear();
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+
+ let alarms = await browser.alarms.getAll();
+ browser.test.assertEq(0, alarms.length, "alarm was removed");
+
+ browser.test.notifyPass("alarm-single-arg");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-single-arg");
+ yield extension.unload();
+});
+
+
+add_task(function* test_get_get_all_clear_all_alarms() {
+ async function backgroundScript() {
+ const ALARM_NAME = "test_alarm";
+
+ let suffixes = [0, 1, 2];
+
+ for (let suffix of suffixes) {
+ browser.alarms.create(ALARM_NAME + suffix, {when: Date.now() + (suffix + 1) * 10000});
+ }
+
+ let alarms = await browser.alarms.getAll();
+ browser.test.assertEq(suffixes.length, alarms.length, "expected number of alarms were found");
+ alarms.forEach((alarm, index) => {
+ browser.test.assertEq(ALARM_NAME + index, alarm.name, "alarm has the expected name");
+ });
+
+
+ for (let suffix of suffixes) {
+ let alarm = await browser.alarms.get(ALARM_NAME + suffix);
+ browser.test.assertEq(ALARM_NAME + suffix, alarm.name, "alarm has the expected name");
+ browser.test.sendMessage(`get-${suffix}`);
+ }
+
+ let wasCleared = await browser.alarms.clear(ALARM_NAME + suffixes[0]);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+
+ alarms = await browser.alarms.getAll();
+ browser.test.assertEq(2, alarms.length, "alarm was removed");
+
+ let alarm = await browser.alarms.get(ALARM_NAME + suffixes[0]);
+ browser.test.assertEq(undefined, alarm, "non-existent alarm is undefined");
+ browser.test.sendMessage(`get-invalid`);
+
+ wasCleared = await browser.alarms.clearAll();
+ browser.test.assertTrue(wasCleared, "alarms were cleared");
+
+ alarms = await browser.alarms.getAll();
+ browser.test.assertEq(0, alarms.length, "no alarms exist");
+ browser.test.sendMessage("clearAll");
+ browser.test.sendMessage("clear");
+ browser.test.sendMessage("getAll");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield Promise.all([
+ extension.startup(),
+ extension.awaitMessage("getAll"),
+ extension.awaitMessage("get-0"),
+ extension.awaitMessage("get-1"),
+ extension.awaitMessage("get-2"),
+ extension.awaitMessage("clear"),
+ extension.awaitMessage("get-invalid"),
+ extension.awaitMessage("clearAll"),
+ ]);
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js
new file mode 100644
index 000000000..11407b108
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js
@@ -0,0 +1,33 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_cleared_alarm_does_not_fire() {
+ async function backgroundScript() {
+ let ALARM_NAME = "test_ext_alarms";
+
+ browser.alarms.onAlarm.addListener(alarm => {
+ browser.test.fail("cleared alarm does not fire");
+ browser.test.notifyFail("alarm-cleared");
+ });
+ browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000});
+
+ let wasCleared = await browser.alarms.clear(ALARM_NAME);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ browser.test.notifyPass("alarm-cleared");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-cleared");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js
new file mode 100644
index 000000000..6bcdf4e33
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js
@@ -0,0 +1,44 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_periodic_alarm_fires() {
+ function backgroundScript() {
+ const ALARM_NAME = "test_ext_alarms";
+ let count = 0;
+ let timer;
+
+ browser.alarms.onAlarm.addListener(async alarm => {
+ browser.test.assertEq(alarm.name, ALARM_NAME, "alarm has the expected name");
+ if (count++ === 3) {
+ clearTimeout(timer);
+ let wasCleared = await browser.alarms.clear(ALARM_NAME);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+
+ browser.test.notifyPass("alarm-periodic");
+ }
+ });
+
+ browser.alarms.create(ALARM_NAME, {periodInMinutes: 0.02});
+
+ timer = setTimeout(async () => {
+ browser.test.fail("alarm fired expected number of times");
+
+ let wasCleared = await browser.alarms.clear(ALARM_NAME);
+ browser.test.assertTrue(wasCleared, "alarm was cleared");
+
+ browser.test.notifyFail("alarm-periodic");
+ }, 30000);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-periodic");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js
new file mode 100644
index 000000000..96f61acb5
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js
@@ -0,0 +1,44 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+
+add_task(function* test_duplicate_alarm_name_replaces_alarm() {
+ function backgroundScript() {
+ let count = 0;
+
+ browser.alarms.onAlarm.addListener(async alarm => {
+ if (alarm.name === "master alarm") {
+ browser.alarms.create("child alarm", {delayInMinutes: 0.05});
+ let results = await browser.alarms.getAll();
+
+ browser.test.assertEq(2, results.length, "exactly two alarms exist");
+ browser.test.assertEq("master alarm", results[0].name, "first alarm has the expected name");
+ browser.test.assertEq("child alarm", results[1].name, "second alarm has the expected name");
+
+ if (count++ === 3) {
+ await browser.alarms.clear("master alarm");
+ await browser.alarms.clear("child alarm");
+
+ browser.test.notifyPass("alarm-duplicate");
+ }
+ } else {
+ browser.test.fail("duplicate named alarm replaced existing alarm");
+ browser.test.notifyFail("alarm-duplicate");
+ }
+ });
+
+ browser.alarms.create("master alarm", {delayInMinutes: 0.025, periodInMinutes: 0.025});
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["alarms"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("alarm-duplicate");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js b/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js
new file mode 100644
index 000000000..d653d0e7a
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js
@@ -0,0 +1,64 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+let {Management} = Cu.import("resource://gre/modules/Extension.jsm", {});
+function getNextContext() {
+ return new Promise(resolve => {
+ Management.on("proxy-context-load", function listener(type, context) {
+ Management.off("proxy-context-load", listener);
+ resolve(context);
+ });
+ });
+}
+
+add_task(function* test_storage_api_without_permissions() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ // Force API initialization.
+ void browser.storage;
+ },
+
+ manifest: {
+ permissions: [],
+ },
+ });
+
+ let contextPromise = getNextContext();
+ yield extension.startup();
+
+ let context = yield contextPromise;
+
+ // Force API initialization.
+ void context.apiObj;
+
+ ok(!("storage" in context.apiObj),
+ "The storage API should not be initialized");
+
+ yield extension.unload();
+});
+
+add_task(function* test_storage_api_with_permissions() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ void browser.storage;
+ },
+
+ manifest: {
+ permissions: ["storage"],
+ },
+ });
+
+ let contextPromise = getNextContext();
+ yield extension.startup();
+
+ let context = yield contextPromise;
+
+ // Force API initialization.
+ void context.apiObj;
+
+ equal(typeof context.apiObj.storage, "object",
+ "The storage API should be initialized");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js b/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js
new file mode 100644
index 000000000..3f6672a11
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js
@@ -0,0 +1,91 @@
+/* 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";
+
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+
+const {
+ SchemaAPIManager,
+} = ExtensionCommon;
+
+this.unknownvar = "Some module-global var";
+
+var gUniqueId = 0;
+
+// SchemaAPIManager's loadScript uses loadSubScript to load a script. This
+// requires a local (resource://) URL. So create such a temporary URL for
+// testing.
+function toLocalURI(code) {
+ let dataUrl = `data:charset=utf-8,${encodeURIComponent(code)}`;
+ let uniqueResPart = `need-a-local-uri-for-subscript-loading-${++gUniqueId}`;
+ Services.io.getProtocolHandler("resource")
+ .QueryInterface(Ci.nsIResProtocolHandler)
+ .setSubstitution(uniqueResPart, Services.io.newURI(dataUrl, null, null));
+ return `resource://${uniqueResPart}`;
+}
+
+add_task(function* test_global_isolation() {
+ let manA = new SchemaAPIManager("procA");
+ let manB = new SchemaAPIManager("procB");
+
+ // The "global" variable should be persistent and shared.
+ manA.loadScript(toLocalURI`global.globalVar = 1;`);
+ do_check_eq(manA.global.globalVar, 1);
+ do_check_eq(manA.global.unknownvar, undefined);
+ manA.loadScript(toLocalURI`global.canSeeGlobal = global.globalVar;`);
+ do_check_eq(manA.global.canSeeGlobal, 1);
+
+ // Each loadScript call should have their own scope, and global is shared.
+ manA.loadScript(toLocalURI`this.aVar = 1; global.thisScopeVar = aVar`);
+ do_check_eq(manA.global.aVar, undefined);
+ do_check_eq(manA.global.thisScopeVar, 1);
+ manA.loadScript(toLocalURI`global.differentScopeVar = this.aVar;`);
+ do_check_eq(manA.global.differentScopeVar, undefined);
+ manA.loadScript(toLocalURI`global.cantSeeOtherScope = typeof aVar;`);
+ do_check_eq(manA.global.cantSeeOtherScope, "undefined");
+
+ manB.loadScript(toLocalURI`global.tryReadOtherGlobal = global.tryagain;`);
+ do_check_eq(manA.global.tryReadOtherGlobal, undefined);
+
+ // Cu.import without second argument exports to the caller's global. Let's
+ // verify that it does not leak to the SchemaAPIManager's global.
+ do_check_eq(typeof ExtensionUtils, "undefined"); // Sanity check #1.
+ manA.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`);
+ do_check_eq(manA.global.hasExtUtils, "undefined"); // Sanity check #2
+
+ Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+ do_check_eq(typeof ExtensionUtils, "object"); // Sanity check #3.
+
+ manA.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`);
+ do_check_eq(manA.global.hasExtUtils, "undefined");
+ manB.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`);
+ do_check_eq(manB.global.hasExtUtils, "undefined");
+
+ // Confirm that Cu.import does not leak between SchemaAPIManager globals.
+ manA.loadScript(toLocalURI`
+ Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+ global.hasExtUtils = typeof ExtensionUtils;
+ `);
+ do_check_eq(manA.global.hasExtUtils, "object"); // Sanity check.
+ manB.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`);
+ do_check_eq(manB.global.hasExtUtils, "undefined");
+
+ // Prototype modifications should be isolated.
+ manA.loadScript(toLocalURI`
+ Object.prototype.modifiedByA = "Prrft";
+ global.fromA = {};
+ `);
+ manA.loadScript(toLocalURI`
+ global.fromAagain = {};
+ `);
+ manB.loadScript(toLocalURI`
+ global.fromB = {};
+ `);
+ do_check_eq(manA.global.modifiedByA, "Prrft");
+ do_check_eq(manA.global.fromA.modifiedByA, "Prrft");
+ do_check_eq(manA.global.fromAagain.modifiedByA, "Prrft");
+ do_check_eq(manB.global.modifiedByA, undefined);
+ do_check_eq(manB.global.fromB.modifiedByA, undefined);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js
new file mode 100644
index 000000000..26282fcb9
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js
@@ -0,0 +1,23 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* eslint-disable mozilla/balanced-listeners */
+
+add_task(function* test_DOMContentLoaded_in_generated_background_page() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ function reportListener(event) {
+ browser.test.sendMessage("eventname", event.type);
+ }
+ document.addEventListener("DOMContentLoaded", reportListener);
+ window.addEventListener("load", reportListener);
+ },
+ });
+
+ yield extension.startup();
+ equal("DOMContentLoaded", yield extension.awaitMessage("eventname"));
+ equal("load", yield extension.awaitMessage("eventname"));
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js
new file mode 100644
index 000000000..4bf59b798
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js
@@ -0,0 +1,24 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_reload_generated_background_page() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ if (location.hash !== "#firstrun") {
+ browser.test.sendMessage("first run");
+ location.hash = "#firstrun";
+ browser.test.assertEq("#firstrun", location.hash);
+ location.reload();
+ } else {
+ browser.test.notifyPass("second run");
+ }
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("first run");
+ yield extension.awaitFinish("second run");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js
new file mode 100644
index 000000000..092a9f5b3
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js
@@ -0,0 +1,22 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://testing-common/PlacesTestUtils.jsm");
+
+add_task(function* test_global_history() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ browser.test.sendMessage("background-loaded", location.href);
+ },
+ });
+
+ yield extension.startup();
+
+ let backgroundURL = yield extension.awaitMessage("background-loaded");
+
+ yield extension.unload();
+
+ let exists = yield PlacesTestUtils.isPageInDB(backgroundURL);
+ ok(!exists, "Background URL should not be in history database");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js
new file mode 100644
index 000000000..8e8b5e0b0
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js
@@ -0,0 +1,40 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://gre/modules/Preferences.jsm");
+
+function* testBackgroundPage(expected) {
+ let extension = ExtensionTestUtils.loadExtension({
+ async background() {
+ browser.test.assertEq(window, browser.extension.getBackgroundPage(),
+ "Caller should be able to access itself as a background page");
+ browser.test.assertEq(window, await browser.runtime.getBackgroundPage(),
+ "Caller should be able to access itself as a background page");
+
+ browser.test.sendMessage("incognito", browser.extension.inIncognitoContext);
+ },
+ });
+
+ yield extension.startup();
+
+ let incognito = yield extension.awaitMessage("incognito");
+ equal(incognito, expected.incognito, "Expected incognito value");
+
+ yield extension.unload();
+}
+
+add_task(function* test_background_incognito() {
+ do_print("Test background page incognito value with permanent private browsing disabled");
+
+ yield testBackgroundPage({incognito: false});
+
+ do_print("Test background page incognito value with permanent private browsing enabled");
+
+ Preferences.set("browser.privatebrowsing.autostart", true);
+ do_register_cleanup(() => {
+ Preferences.reset("browser.privatebrowsing.autostart");
+ });
+
+ yield testBackgroundPage({incognito: true});
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js
new file mode 100644
index 000000000..426833edd
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js
@@ -0,0 +1,72 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+function backgroundScript() {
+ let received_ports_number = 0;
+
+ const expected_received_ports_number = 1;
+
+ function countReceivedPorts(port) {
+ received_ports_number++;
+
+ if (port.name == "check-results") {
+ browser.runtime.onConnect.removeListener(countReceivedPorts);
+
+ browser.test.assertEq(expected_received_ports_number, received_ports_number, "invalid connect should not create a port");
+
+ browser.test.notifyPass("runtime.connect invalid params");
+ }
+ }
+
+ browser.runtime.onConnect.addListener(countReceivedPorts);
+
+ let childFrame = document.createElement("iframe");
+ childFrame.src = "extensionpage.html";
+ document.body.appendChild(childFrame);
+}
+
+function senderScript() {
+ let detected_invalid_connect_params = 0;
+
+ const invalid_connect_params = [
+ // too many params
+ ["fake-extensions-id", {name: "fake-conn-name"}, "unexpected third params"],
+ // invalid params format
+ [{}, {}],
+ ["fake-extensions-id", "invalid-connect-info-format"],
+ ];
+ const expected_detected_invalid_connect_params = invalid_connect_params.length;
+
+ function assertInvalidConnectParamsException(params) {
+ try {
+ browser.runtime.connect(...params);
+ } catch (e) {
+ detected_invalid_connect_params++;
+ browser.test.assertTrue(e.toString().indexOf("Incorrect argument types for runtime.connect.") >= 0, "exception message is correct");
+ }
+ }
+ for (let params of invalid_connect_params) {
+ assertInvalidConnectParamsException(params);
+ }
+ browser.test.assertEq(expected_detected_invalid_connect_params, detected_invalid_connect_params, "all invalid runtime.connect params detected");
+
+ browser.runtime.connect(browser.runtime.id, {name: "check-results"});
+}
+
+let extensionData = {
+ background: backgroundScript,
+ files: {
+ "senderScript.js": senderScript,
+ "extensionpage.html": `<!DOCTYPE html><meta charset="utf-8"><script src="senderScript.js"></script>`,
+ },
+};
+
+add_task(function* test_backgroundRuntimeConnectParams() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("runtime.connect invalid params");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js
new file mode 100644
index 000000000..c5f2f1332
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js
@@ -0,0 +1,45 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* testBackgroundWindow() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ browser.test.log("background script executed");
+
+ browser.test.sendMessage("background-script-load");
+
+ let img = document.createElement("img");
+ img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
+ document.body.appendChild(img);
+
+ img.onload = () => {
+ browser.test.log("image loaded");
+
+ let iframe = document.createElement("iframe");
+ iframe.src = "about:blank?1";
+
+ iframe.onload = () => {
+ browser.test.log("iframe loaded");
+ setTimeout(() => {
+ browser.test.notifyPass("background sub-window test done");
+ }, 0);
+ };
+ document.body.appendChild(iframe);
+ };
+ },
+ });
+
+ let loadCount = 0;
+ extension.onMessage("background-script-load", () => {
+ loadCount++;
+ });
+
+ yield extension.startup();
+
+ yield extension.awaitFinish("background sub-window test done");
+
+ equal(loadCount, 1, "background script loaded only once");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js
new file mode 100644
index 000000000..948e2913e
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js
@@ -0,0 +1,34 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* testBackgroundWindowProperties() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ let expectedValues = {
+ screenX: 0,
+ screenY: 0,
+ outerWidth: 0,
+ outerHeight: 0,
+ };
+
+ for (let k in window) {
+ try {
+ if (k in expectedValues) {
+ browser.test.assertEq(expectedValues[k], window[k],
+ `should return the expected value for window property: ${k}`);
+ } else {
+ void window[k];
+ }
+ } catch (e) {
+ browser.test.assertEq(null, e, `unexpected exception accessing window property: ${k}`);
+ }
+ }
+
+ browser.test.notifyPass("background.testWindowProperties.done");
+ },
+ });
+ yield extension.startup();
+ yield extension.awaitFinish("background.testWindowProperties.done");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js b/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js
new file mode 100644
index 000000000..56a14e189
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js
@@ -0,0 +1,190 @@
+"use strict";
+
+const global = this;
+
+Cu.import("resource://gre/modules/Timer.jsm");
+
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+Cu.import("resource://gre/modules/ExtensionUtils.jsm");
+
+var {
+ BaseContext,
+} = ExtensionCommon;
+
+var {
+ EventManager,
+ SingletonEventManager,
+} = ExtensionUtils;
+
+class StubContext extends BaseContext {
+ constructor() {
+ let fakeExtension = {id: "test@web.extension"};
+ super("testEnv", fakeExtension);
+ this.sandbox = Cu.Sandbox(global);
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+}
+
+
+add_task(function* test_post_unload_promises() {
+ let context = new StubContext();
+
+ let fail = result => {
+ ok(false, `Unexpected callback: ${result}`);
+ };
+
+ // Make sure promises resolve normally prior to unload.
+ let promises = [
+ context.wrapPromise(Promise.resolve()),
+ context.wrapPromise(Promise.reject({message: ""})).catch(() => {}),
+ ];
+
+ yield Promise.all(promises);
+
+ // Make sure promises that resolve after unload do not trigger
+ // resolution handlers.
+
+ context.wrapPromise(Promise.resolve("resolved"))
+ .then(fail);
+
+ context.wrapPromise(Promise.reject({message: "rejected"}))
+ .then(fail, fail);
+
+ context.unload();
+
+ // The `setTimeout` ensures that we return to the event loop after
+ // promise resolution, which means we're guaranteed to return after
+ // any micro-tasks that get enqueued by the resolution handlers above.
+ yield new Promise(resolve => setTimeout(resolve, 0));
+});
+
+
+add_task(function* test_post_unload_listeners() {
+ let context = new StubContext();
+
+ let fireEvent;
+ let onEvent = new EventManager(context, "onEvent", fire => {
+ fireEvent = fire;
+ return () => {};
+ });
+
+ let fireSingleton;
+ let onSingleton = new SingletonEventManager(context, "onSingleton", callback => {
+ fireSingleton = () => {
+ Promise.resolve().then(callback);
+ };
+ return () => {};
+ });
+
+ let fail = event => {
+ ok(false, `Unexpected event: ${event}`);
+ };
+
+ // Check that event listeners aren't called after they've been removed.
+ onEvent.addListener(fail);
+ onSingleton.addListener(fail);
+
+ let promises = [
+ new Promise(resolve => onEvent.addListener(resolve)),
+ new Promise(resolve => onSingleton.addListener(resolve)),
+ ];
+
+ fireEvent("onEvent");
+ fireSingleton("onSingleton");
+
+ // Both `fireEvent` calls are dispatched asynchronously, so they won't
+ // have fired by this point. The `fail` listeners that we remove now
+ // should not be called, even though the events have already been
+ // enqueued.
+ onEvent.removeListener(fail);
+ onSingleton.removeListener(fail);
+
+ // Wait for the remaining listeners to be called, which should always
+ // happen after the `fail` listeners would normally be called.
+ yield Promise.all(promises);
+
+ // Check that event listeners aren't called after the context has
+ // unloaded.
+ onEvent.addListener(fail);
+ onSingleton.addListener(fail);
+
+ // The EventManager `fire` callback always dispatches events
+ // asynchronously, so we need to test that any pending event callbacks
+ // aren't fired after the context unloads. We also need to test that
+ // any `fire` calls that happen *after* the context is unloaded also
+ // do not trigger callbacks.
+ fireEvent("onEvent");
+ Promise.resolve("onEvent").then(fireEvent);
+
+ fireSingleton("onSingleton");
+ Promise.resolve("onSingleton").then(fireSingleton);
+
+ context.unload();
+
+ // The `setTimeout` ensures that we return to the event loop after
+ // promise resolution, which means we're guaranteed to return after
+ // any micro-tasks that get enqueued by the resolution handlers above.
+ yield new Promise(resolve => setTimeout(resolve, 0));
+});
+
+class Context extends BaseContext {
+ constructor(principal) {
+ let fakeExtension = {id: "test@web.extension"};
+ super("testEnv", fakeExtension);
+ Object.defineProperty(this, "principal", {
+ value: principal,
+ configurable: true,
+ });
+ this.sandbox = Cu.Sandbox(principal, {wantXrays: false});
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+}
+
+let ssm = Services.scriptSecurityManager;
+const PRINCIPAL1 = ssm.createCodebasePrincipalFromOrigin("http://www.example.org");
+const PRINCIPAL2 = ssm.createCodebasePrincipalFromOrigin("http://www.somethingelse.org");
+
+// Test that toJSON() works in the json sandbox
+add_task(function* test_stringify_toJSON() {
+ let context = new Context(PRINCIPAL1);
+ let obj = Cu.evalInSandbox("({hidden: true, toJSON() { return {visible: true}; } })", context.sandbox);
+
+ let stringified = context.jsonStringify(obj);
+ let expected = JSON.stringify({visible: true});
+ equal(stringified, expected, "Stringified object with toJSON() method is as expected");
+});
+
+// Test that stringifying in inaccessible property throws
+add_task(function* test_stringify_inaccessible() {
+ let context = new Context(PRINCIPAL1);
+ let sandbox = context.sandbox;
+ let sandbox2 = Cu.Sandbox(PRINCIPAL2);
+
+ Cu.waiveXrays(sandbox).subobj = Cu.evalInSandbox("({ subobject: true })", sandbox2);
+ let obj = Cu.evalInSandbox("({ local: true, nested: subobj })", sandbox);
+ Assert.throws(() => {
+ context.jsonStringify(obj);
+ });
+});
+
+add_task(function* test_stringify_accessible() {
+ // Test that an accessible property from another global is included
+ let principal = Cu.getObjectPrincipal(Cu.Sandbox([PRINCIPAL1, PRINCIPAL2]));
+ let context = new Context(principal);
+ let sandbox = context.sandbox;
+ let sandbox2 = Cu.Sandbox(PRINCIPAL2);
+
+ Cu.waiveXrays(sandbox).subobj = Cu.evalInSandbox("({ subobject: true })", sandbox2);
+ let obj = Cu.evalInSandbox("({ local: true, nested: subobj })", sandbox);
+ let stringified = context.jsonStringify(obj);
+
+ let expected = JSON.stringify({local: true, nested: {subobject: true}});
+ equal(stringified, expected, "Stringified object with accessible property is as expected");
+});
+
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js
new file mode 100644
index 000000000..058b9b18c
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js
@@ -0,0 +1,76 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_downloads_api_namespace_and_permissions() {
+ function backgroundScript() {
+ browser.test.assertTrue(!!browser.downloads, "`downloads` API is present.");
+ browser.test.assertTrue(!!browser.downloads.FilenameConflictAction,
+ "`downloads.FilenameConflictAction` enum is present.");
+ browser.test.assertTrue(!!browser.downloads.InterruptReason,
+ "`downloads.InterruptReason` enum is present.");
+ browser.test.assertTrue(!!browser.downloads.DangerType,
+ "`downloads.DangerType` enum is present.");
+ browser.test.assertTrue(!!browser.downloads.State,
+ "`downloads.State` enum is present.");
+ browser.test.notifyPass("downloads tests");
+ }
+
+ let extensionData = {
+ background: backgroundScript,
+ manifest: {
+ permissions: ["downloads", "downloads.open", "downloads.shelf"],
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitFinish("downloads tests");
+ yield extension.unload();
+});
+
+add_task(function* test_downloads_open_permission() {
+ function backgroundScript() {
+ browser.test.assertFalse("open" in browser.downloads,
+ "`downloads.open` permission is required.");
+ browser.test.notifyPass("downloads tests");
+ }
+
+ let extensionData = {
+ background: backgroundScript,
+ manifest: {
+ permissions: ["downloads"],
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitFinish("downloads tests");
+ yield extension.unload();
+});
+
+add_task(function* test_downloads_open() {
+ async function backgroundScript() {
+ await browser.test.assertRejects(
+ browser.downloads.open(10),
+ "Invalid download id 10",
+ "The error is informative.");
+
+ browser.test.notifyPass("downloads tests");
+
+ // TODO: Once downloads.{pause,cancel,resume} lands (bug 1245602) test that this gives a good
+ // error when called with an incompleted download.
+ }
+
+ let extensionData = {
+ background: backgroundScript,
+ manifest: {
+ permissions: ["downloads", "downloads.open"],
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitFinish("downloads tests");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js
new file mode 100644
index 000000000..37ddd4d7c
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js
@@ -0,0 +1,354 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* global OS */
+
+Cu.import("resource://gre/modules/osfile.jsm");
+Cu.import("resource://gre/modules/Downloads.jsm");
+
+const gServer = createHttpServer();
+gServer.registerDirectory("/data/", do_get_file("data"));
+
+const WINDOWS = AppConstants.platform == "win";
+
+const BASE = `http://localhost:${gServer.identity.primaryPort}/data`;
+const FILE_NAME = "file_download.txt";
+const FILE_URL = BASE + "/" + FILE_NAME;
+const FILE_NAME_UNIQUE = "file_download(1).txt";
+const FILE_LEN = 46;
+
+let downloadDir;
+
+function setup() {
+ downloadDir = FileUtils.getDir("TmpD", ["downloads"]);
+ downloadDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_print(`Using download directory ${downloadDir.path}`);
+
+ Services.prefs.setIntPref("browser.download.folderList", 2);
+ Services.prefs.setComplexValue("browser.download.dir", Ci.nsIFile, downloadDir);
+
+ do_register_cleanup(() => {
+ Services.prefs.clearUserPref("browser.download.folderList");
+ Services.prefs.clearUserPref("browser.download.dir");
+
+ let entries = downloadDir.directoryEntries;
+ while (entries.hasMoreElements()) {
+ let entry = entries.getNext().QueryInterface(Ci.nsIFile);
+ ok(false, `Leftover file ${entry.path} in download directory`);
+ entry.remove(false);
+ }
+
+ downloadDir.remove(false);
+ });
+}
+
+function backgroundScript() {
+ let blobUrl;
+ browser.test.onMessage.addListener(async (msg, ...args) => {
+ if (msg == "download.request") {
+ let options = args[0];
+
+ if (options.blobme) {
+ let blob = new Blob(options.blobme);
+ delete options.blobme;
+ blobUrl = options.url = window.URL.createObjectURL(blob);
+ }
+
+ try {
+ let id = await browser.downloads.download(options);
+ browser.test.sendMessage("download.done", {status: "success", id});
+ } catch (error) {
+ browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
+ }
+ } else if (msg == "killTheBlob") {
+ window.URL.revokeObjectURL(blobUrl);
+ blobUrl = null;
+ }
+ });
+
+ browser.test.sendMessage("ready");
+}
+
+// This function is a bit of a sledgehammer, it looks at every download
+// the browser knows about and waits for all active downloads to complete.
+// But we only start one at a time and only do a handful in total, so
+// this lets us test download() without depending on anything else.
+async function waitForDownloads() {
+ let list = await Downloads.getList(Downloads.ALL);
+ let downloads = await list.getAll();
+
+ let inprogress = downloads.filter(dl => !dl.stopped);
+ return Promise.all(inprogress.map(dl => dl.whenSucceeded()));
+}
+
+// Create a file in the downloads directory.
+function touch(filename) {
+ let file = downloadDir.clone();
+ file.append(filename);
+ file.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
+}
+
+// Remove a file in the downloads directory.
+function remove(filename, recursive = false) {
+ let file = downloadDir.clone();
+ file.append(filename);
+ file.remove(recursive);
+}
+
+add_task(function* test_downloads() {
+ setup();
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: `(${backgroundScript})()`,
+ manifest: {
+ permissions: ["downloads"],
+ },
+ });
+
+ function download(options) {
+ extension.sendMessage("download.request", options);
+ return extension.awaitMessage("download.done");
+ }
+
+ async function testDownload(options, localFile, expectedSize, description) {
+ let msg = await download(options);
+ equal(msg.status, "success", `downloads.download() works with ${description}`);
+
+ await waitForDownloads();
+
+ let localPath = downloadDir.clone();
+ let parts = Array.isArray(localFile) ? localFile : [localFile];
+
+ parts.map(p => localPath.append(p));
+ equal(localPath.fileSize, expectedSize, "Downloaded file has expected size");
+ localPath.remove(false);
+ }
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+ do_print("extension started");
+
+ // Call download() with just the url property.
+ yield testDownload({url: FILE_URL}, FILE_NAME, FILE_LEN, "just source");
+
+ // Call download() with a filename property.
+ yield testDownload({
+ url: FILE_URL,
+ filename: "newpath.txt",
+ }, "newpath.txt", FILE_LEN, "source and filename");
+
+ // Call download() with a filename with subdirs.
+ yield testDownload({
+ url: FILE_URL,
+ filename: "sub/dir/file",
+ }, ["sub", "dir", "file"], FILE_LEN, "source and filename with subdirs");
+
+ // Call download() with a filename with existing subdirs.
+ yield testDownload({
+ url: FILE_URL,
+ filename: "sub/dir/file2",
+ }, ["sub", "dir", "file2"], FILE_LEN, "source and filename with existing subdirs");
+
+ // Only run Windows path separator test on Windows.
+ if (WINDOWS) {
+ // Call download() with a filename with Windows path separator.
+ yield testDownload({
+ url: FILE_URL,
+ filename: "sub\\dir\\file3",
+ }, ["sub", "dir", "file3"], FILE_LEN, "filename with Windows path separator");
+ }
+ remove("sub", true);
+
+ // Call download(), filename with subdir, skipping parts.
+ yield testDownload({
+ url: FILE_URL,
+ filename: "skip//part",
+ }, ["skip", "part"], FILE_LEN, "source, filename, with subdir, skipping parts");
+ remove("skip", true);
+
+ // Check conflictAction of "uniquify".
+ touch(FILE_NAME);
+ yield testDownload({
+ url: FILE_URL,
+ conflictAction: "uniquify",
+ }, FILE_NAME_UNIQUE, FILE_LEN, "conflictAction=uniquify");
+ // todo check that preexisting file was not modified?
+ remove(FILE_NAME);
+
+ // Check conflictAction of "overwrite".
+ touch(FILE_NAME);
+ yield testDownload({
+ url: FILE_URL,
+ conflictAction: "overwrite",
+ }, FILE_NAME, FILE_LEN, "conflictAction=overwrite");
+
+ // Try to download in invalid url
+ yield download({url: "this is not a valid URL"}).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with invalid url");
+ ok(/not a valid URL/.test(msg.errmsg), "error message for invalid url is correct");
+ });
+
+ // Try to download to an empty path.
+ yield download({
+ url: FILE_URL,
+ filename: "",
+ }).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with empty filename");
+ equal(msg.errmsg, "filename must not be empty", "error message for empty filename is correct");
+ });
+
+ // Try to download to an absolute path.
+ const absolutePath = OS.Path.join(WINDOWS ? "\\tmp" : "/tmp", "file_download.txt");
+ yield download({
+ url: FILE_URL,
+ filename: absolutePath,
+ }).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with absolute filename");
+ equal(msg.errmsg, "filename must not be an absolute path", `error message for absolute path (${absolutePath}) is correct`);
+ });
+
+ if (WINDOWS) {
+ yield download({
+ url: FILE_URL,
+ filename: "C:\\file_download.txt",
+ }).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with absolute filename");
+ equal(msg.errmsg, "filename must not be an absolute path", "error message for absolute path with drive letter is correct");
+ });
+ }
+
+ // Try to download to a relative path containing ..
+ yield download({
+ url: FILE_URL,
+ filename: OS.Path.join("..", "file_download.txt"),
+ }).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with back-references");
+ equal(msg.errmsg, "filename must not contain back-references (..)", "error message for back-references is correct");
+ });
+
+ // Try to download to a long relative path containing ..
+ yield download({
+ url: FILE_URL,
+ filename: OS.Path.join("foo", "..", "..", "file_download.txt"),
+ }).then(msg => {
+ equal(msg.status, "error", "downloads.download() fails with back-references");
+ equal(msg.errmsg, "filename must not contain back-references (..)", "error message for back-references is correct");
+ });
+
+ // Try to download a blob url
+ const BLOB_STRING = "Hello, world";
+ yield testDownload({
+ blobme: [BLOB_STRING],
+ filename: FILE_NAME,
+ }, FILE_NAME, BLOB_STRING.length, "blob url");
+ extension.sendMessage("killTheBlob");
+
+ // Try to download a blob url without a given filename
+ yield testDownload({
+ blobme: [BLOB_STRING],
+ }, "download", BLOB_STRING.length, "blob url with no filename");
+ extension.sendMessage("killTheBlob");
+
+ yield extension.unload();
+});
+
+add_task(function* test_download_post() {
+ const server = createHttpServer();
+ const url = `http://localhost:${server.identity.primaryPort}/post-log`;
+
+ let received;
+ server.registerPathHandler("/post-log", request => {
+ received = request;
+ });
+
+ // Confirm received vs. expected values.
+ function confirm(method, headers = {}, body) {
+ equal(received.method, method, "method is correct");
+
+ for (let name in headers) {
+ ok(received.hasHeader(name), `header ${name} received`);
+ equal(received.getHeader(name), headers[name], `header ${name} is correct`);
+ }
+
+ if (body) {
+ const str = NetUtil.readInputStreamToString(received.bodyInputStream,
+ received.bodyInputStream.available());
+ equal(str, body, "body is correct");
+ }
+ }
+
+ function background() {
+ browser.test.onMessage.addListener(async options => {
+ try {
+ await browser.downloads.download(options);
+ } catch (err) {
+ browser.test.sendMessage("done", {err: err.message});
+ }
+ });
+ browser.downloads.onChanged.addListener(({state}) => {
+ if (state && state.current === "complete") {
+ browser.test.sendMessage("done", {ok: true});
+ }
+ });
+ }
+
+ const manifest = {permissions: ["downloads"]};
+ const extension = ExtensionTestUtils.loadExtension({background, manifest});
+ yield extension.startup();
+
+ function download(options) {
+ options.url = url;
+ options.conflictAction = "overwrite";
+
+ extension.sendMessage(options);
+ return extension.awaitMessage("done");
+ }
+
+ // Test method option.
+ let result = yield download({});
+ ok(result.ok, "download works without the method option, defaults to GET");
+ confirm("GET");
+
+ result = yield download({method: "PUT"});
+ ok(!result.ok, "download rejected with PUT method");
+ ok(/method: Invalid enumeration/.test(result.err), "descriptive error message");
+
+ result = yield download({method: "POST"});
+ ok(result.ok, "download works with POST method");
+ confirm("POST");
+
+ // Test body option values.
+ result = yield download({body: []});
+ ok(!result.ok, "download rejected because of non-string body");
+ ok(/body: Expected string/.test(result.err), "descriptive error message");
+
+ result = yield download({method: "POST", body: "of work"});
+ ok(result.ok, "download works with POST method and body");
+ confirm("POST", {"Content-Length": 7}, "of work");
+
+ // Test custom headers.
+ result = yield download({headers: [{name: "X-Custom"}]});
+ ok(!result.ok, "download rejected because of missing header value");
+ ok(/"value" is required/.test(result.err), "descriptive error message");
+
+ result = yield download({headers: [{name: "X-Custom", value: "13"}]});
+ ok(result.ok, "download works with a custom header");
+ confirm("GET", {"X-Custom": "13"});
+
+ // Test forbidden headers.
+ result = yield download({headers: [{name: "DNT", value: "1"}]});
+ ok(!result.ok, "download rejected because of forbidden header name DNT");
+ ok(/Forbidden request header/.test(result.err), "descriptive error message");
+
+ result = yield download({headers: [{name: "Proxy-Connection", value: "keep"}]});
+ ok(!result.ok, "download rejected because of forbidden header name prefix Proxy-");
+ ok(/Forbidden request header/.test(result.err), "descriptive error message");
+
+ result = yield download({headers: [{name: "Sec-ret", value: "13"}]});
+ ok(!result.ok, "download rejected because of forbidden header name prefix Sec-");
+ ok(/Forbidden request header/.test(result.err), "descriptive error message");
+
+ remove("post-log");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js
new file mode 100644
index 000000000..d08aab666
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js
@@ -0,0 +1,862 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://gre/modules/Downloads.jsm");
+
+const server = createHttpServer();
+server.registerDirectory("/data/", do_get_file("data"));
+
+const ROOT = `http://localhost:${server.identity.primaryPort}`;
+const BASE = `${ROOT}/data`;
+const TXT_FILE = "file_download.txt";
+const TXT_URL = BASE + "/" + TXT_FILE;
+
+// Keep these in sync with code in interruptible.sjs
+const INT_PARTIAL_LEN = 15;
+const INT_TOTAL_LEN = 31;
+
+const TEST_DATA = "This is 31 bytes of sample data";
+const TOTAL_LEN = TEST_DATA.length;
+const PARTIAL_LEN = 15;
+
+// A handler to let us systematically test pausing/resuming/canceling
+// of downloads. This target represents a small text file but a simple
+// GET will stall after sending part of the data, to give the test code
+// a chance to pause or do other operations on an in-progress download.
+// A resumed download (ie, a GET with a Range: header) will allow the
+// download to complete.
+function handleRequest(request, response) {
+ response.setHeader("Content-Type", "text/plain", false);
+
+ if (request.hasHeader("Range")) {
+ let start, end;
+ let matches = request.getHeader("Range")
+ .match(/^\s*bytes=(\d+)?-(\d+)?\s*$/);
+ if (matches != null) {
+ start = matches[1] ? parseInt(matches[1], 10) : 0;
+ end = matches[2] ? parseInt(matches[2], 10) : (TOTAL_LEN - 1);
+ }
+
+ if (end == undefined || end >= TOTAL_LEN) {
+ response.setStatusLine(request.httpVersion, 416, "Requested Range Not Satisfiable");
+ response.setHeader("Content-Range", `*/${TOTAL_LEN}`, false);
+ response.finish();
+ return;
+ }
+
+ response.setStatusLine(request.httpVersion, 206, "Partial Content");
+ response.setHeader("Content-Range", `${start}-${end}/${TOTAL_LEN}`, false);
+ response.write(TEST_DATA.slice(start, end + 1));
+ } else {
+ response.processAsync();
+ response.setHeader("Content-Length", `${TOTAL_LEN}`, false);
+ response.write(TEST_DATA.slice(0, PARTIAL_LEN));
+ }
+
+ do_register_cleanup(() => {
+ try {
+ response.finish();
+ } catch (e) {
+ // This will throw, but we don't care at this point.
+ }
+ });
+}
+
+server.registerPathHandler("/interruptible.html", handleRequest);
+
+let interruptibleCount = 0;
+function getInterruptibleUrl() {
+ let n = interruptibleCount++;
+ return `${ROOT}/interruptible.html?count=${n}`;
+}
+
+function backgroundScript() {
+ let events = new Set();
+ let eventWaiter = null;
+
+ browser.downloads.onCreated.addListener(data => {
+ events.add({type: "onCreated", data});
+ if (eventWaiter) {
+ eventWaiter();
+ }
+ });
+
+ browser.downloads.onChanged.addListener(data => {
+ events.add({type: "onChanged", data});
+ if (eventWaiter) {
+ eventWaiter();
+ }
+ });
+
+ browser.downloads.onErased.addListener(data => {
+ events.add({type: "onErased", data});
+ if (eventWaiter) {
+ eventWaiter();
+ }
+ });
+
+ // Returns a promise that will resolve when the given list of expected
+ // events have all been seen. By default, succeeds only if the exact list
+ // of expected events is seen in the given order. options.exact can be
+ // set to false to allow other events and options.inorder can be set to
+ // false to allow the events to arrive in any order.
+ function waitForEvents(expected, options = {}) {
+ function compare(a, b) {
+ if (typeof b == "object" && b != null) {
+ if (typeof a != "object") {
+ return false;
+ }
+ return Object.keys(b).every(fld => compare(a[fld], b[fld]));
+ }
+ return (a == b);
+ }
+
+ const exact = ("exact" in options) ? options.exact : true;
+ const inorder = ("inorder" in options) ? options.inorder : true;
+ return new Promise((resolve, reject) => {
+ function check() {
+ function fail(msg) {
+ browser.test.fail(msg);
+ reject(new Error(msg));
+ }
+ if (events.size < expected.length) {
+ return;
+ }
+ if (exact && expected.length < events.size) {
+ fail(`Got ${events.size} events but only expected ${expected.length}`);
+ return;
+ }
+
+ let remaining = new Set(events);
+ if (inorder) {
+ for (let event of events) {
+ if (compare(event, expected[0])) {
+ expected.shift();
+ remaining.delete(event);
+ }
+ }
+ } else {
+ expected = expected.filter(val => {
+ for (let remainingEvent of remaining) {
+ if (compare(remainingEvent, val)) {
+ remaining.delete(remainingEvent);
+ return false;
+ }
+ }
+ return true;
+ });
+ }
+
+ // Events that did occur have been removed from expected so if
+ // expected is empty, we're done. If we didn't see all the
+ // expected events and we're not looking for an exact match,
+ // then we just may not have seen the event yet, so return without
+ // failing and check() will be called again when a new event arrives.
+ if (expected.length == 0) {
+ events = remaining;
+ eventWaiter = null;
+ resolve();
+ } else if (exact) {
+ fail(`Mismatched event: expecting ${JSON.stringify(expected[0])} but got ${JSON.stringify(Array.from(remaining)[0])}`);
+ }
+ }
+ eventWaiter = check;
+ check();
+ });
+ }
+
+ browser.test.onMessage.addListener(async (msg, ...args) => {
+ let match = msg.match(/(\w+).request$/);
+ if (!match) {
+ return;
+ }
+
+ let what = match[1];
+ if (what == "waitForEvents") {
+ try {
+ await waitForEvents(...args);
+ browser.test.sendMessage("waitForEvents.done", {status: "success"});
+ } catch (error) {
+ browser.test.sendMessage("waitForEvents.done", {status: "error", errmsg: error.message});
+ }
+ } else if (what == "clearEvents") {
+ events = new Set();
+ browser.test.sendMessage("clearEvents.done", {status: "success"});
+ } else {
+ try {
+ let result = await browser.downloads[what](...args);
+ browser.test.sendMessage(`${what}.done`, {status: "success", result});
+ } catch (error) {
+ browser.test.sendMessage(`${what}.done`, {status: "error", errmsg: error.message});
+ }
+ }
+ });
+
+ browser.test.sendMessage("ready");
+}
+
+let downloadDir;
+let extension;
+
+async function clearDownloads(callback) {
+ let list = await Downloads.getList(Downloads.ALL);
+ let downloads = await list.getAll();
+
+ await Promise.all(downloads.map(download => list.remove(download)));
+
+ return downloads;
+}
+
+function runInExtension(what, ...args) {
+ extension.sendMessage(`${what}.request`, ...args);
+ return extension.awaitMessage(`${what}.done`);
+}
+
+// This is pretty simplistic, it looks for a progress update for a
+// download of the given url in which the total bytes are exactly equal
+// to the given value. Unless you know exactly how data will arrive from
+// the server (eg see interruptible.sjs), it probably isn't very useful.
+async function waitForProgress(url, bytes) {
+ let list = await Downloads.getList(Downloads.ALL);
+
+ return new Promise(resolve => {
+ const view = {
+ onDownloadChanged(download) {
+ if (download.source.url == url && download.currentBytes == bytes) {
+ list.removeView(view);
+ resolve();
+ }
+ },
+ };
+ list.addView(view);
+ });
+}
+
+add_task(function* setup() {
+ const nsIFile = Ci.nsIFile;
+ downloadDir = FileUtils.getDir("TmpD", ["downloads"]);
+ downloadDir.createUnique(nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_print(`downloadDir ${downloadDir.path}`);
+
+ Services.prefs.setIntPref("browser.download.folderList", 2);
+ Services.prefs.setComplexValue("browser.download.dir", nsIFile, downloadDir);
+
+ do_register_cleanup(() => {
+ Services.prefs.clearUserPref("browser.download.folderList");
+ Services.prefs.clearUserPref("browser.download.dir");
+ downloadDir.remove(true);
+
+ return clearDownloads();
+ });
+
+ yield clearDownloads().then(downloads => {
+ do_print(`removed ${downloads.length} pre-existing downloads from history`);
+ });
+
+ extension = ExtensionTestUtils.loadExtension({
+ background: backgroundScript,
+ manifest: {
+ permissions: ["downloads"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+});
+
+add_task(function* test_events() {
+ let msg = yield runInExtension("download", {url: TXT_URL});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id, url: TXT_URL}},
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "complete",
+ },
+ },
+ },
+ ]);
+ equal(msg.status, "success", "got onCreated and onChanged events");
+});
+
+add_task(function* test_cancel() {
+ let url = getInterruptibleUrl();
+ do_print(url);
+ let msg = yield runInExtension("download", {url});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ let progressPromise = waitForProgress(url, INT_PARTIAL_LEN);
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id}},
+ ]);
+ equal(msg.status, "success", "got created and changed events");
+
+ yield progressPromise;
+ do_print(`download reached ${INT_PARTIAL_LEN} bytes`);
+
+ msg = yield runInExtension("cancel", id);
+ equal(msg.status, "success", "cancel() succeeded");
+
+ // This sequence of events is bogus (bug 1256243)
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ state: {
+ previous: "in_progress",
+ current: "interrupted",
+ },
+ paused: {
+ previous: false,
+ current: true,
+ },
+ },
+ }, {
+ type: "onChanged",
+ data: {
+ id,
+ error: {
+ previous: null,
+ current: "USER_CANCELED",
+ },
+ },
+ }, {
+ type: "onChanged",
+ data: {
+ id,
+ paused: {
+ previous: true,
+ current: false,
+ },
+ },
+ },
+ ]);
+ equal(msg.status, "success", "got onChanged events corresponding to cancel()");
+
+ msg = yield runInExtension("search", {error: "USER_CANCELED"});
+ equal(msg.status, "success", "search() succeeded");
+ equal(msg.result.length, 1, "search() found 1 download");
+ equal(msg.result[0].id, id, "download.id is correct");
+ equal(msg.result[0].state, "interrupted", "download.state is correct");
+ equal(msg.result[0].paused, false, "download.paused is correct");
+ equal(msg.result[0].canResume, false, "download.canResume is correct");
+ equal(msg.result[0].error, "USER_CANCELED", "download.error is correct");
+ equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct");
+ equal(msg.result[0].exists, false, "download.exists is correct");
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "error", "cannot pause a canceled download");
+
+ msg = yield runInExtension("resume", id);
+ equal(msg.status, "error", "cannot resume a canceled download");
+});
+
+add_task(function* test_pauseresume() {
+ let url = getInterruptibleUrl();
+ let msg = yield runInExtension("download", {url});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ let progressPromise = waitForProgress(url, INT_PARTIAL_LEN);
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id}},
+ ]);
+ equal(msg.status, "success", "got created and changed events");
+
+ yield progressPromise;
+ do_print(`download reached ${INT_PARTIAL_LEN} bytes`);
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "success", "pause() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "interrupted",
+ },
+ paused: {
+ previous: false,
+ current: true,
+ },
+ canResume: {
+ previous: false,
+ current: true,
+ },
+ },
+ }, {
+ type: "onChanged",
+ data: {
+ id,
+ error: {
+ previous: null,
+ current: "USER_CANCELED",
+ },
+ },
+ }]);
+ equal(msg.status, "success", "got onChanged event corresponding to pause");
+
+ msg = yield runInExtension("search", {paused: true});
+ equal(msg.status, "success", "search() succeeded");
+ equal(msg.result.length, 1, "search() found 1 download");
+ equal(msg.result[0].id, id, "download.id is correct");
+ equal(msg.result[0].state, "interrupted", "download.state is correct");
+ equal(msg.result[0].paused, true, "download.paused is correct");
+ equal(msg.result[0].canResume, true, "download.canResume is correct");
+ equal(msg.result[0].error, "USER_CANCELED", "download.error is correct");
+ equal(msg.result[0].bytesReceived, INT_PARTIAL_LEN, "download.bytesReceived is correct");
+ equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct");
+ equal(msg.result[0].exists, false, "download.exists is correct");
+
+ msg = yield runInExtension("search", {error: "USER_CANCELED"});
+ equal(msg.status, "success", "search() succeeded");
+ let found = msg.result.filter(item => item.id == id);
+ equal(found.length, 1, "search() by error found the paused download");
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "error", "cannot pause an already paused download");
+
+ msg = yield runInExtension("resume", id);
+ equal(msg.status, "success", "resume() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "interrupted",
+ current: "in_progress",
+ },
+ paused: {
+ previous: true,
+ current: false,
+ },
+ canResume: {
+ previous: true,
+ current: false,
+ },
+ error: {
+ previous: "USER_CANCELED",
+ current: null,
+ },
+ },
+ },
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "complete",
+ },
+ },
+ },
+ ]);
+ equal(msg.status, "success", "got onChanged events for resume and complete");
+
+ msg = yield runInExtension("search", {id});
+ equal(msg.status, "success", "search() succeeded");
+ equal(msg.result.length, 1, "search() found 1 download");
+ equal(msg.result[0].state, "complete", "download.state is correct");
+ equal(msg.result[0].paused, false, "download.paused is correct");
+ equal(msg.result[0].canResume, false, "download.canResume is correct");
+ equal(msg.result[0].error, null, "download.error is correct");
+ equal(msg.result[0].bytesReceived, INT_TOTAL_LEN, "download.bytesReceived is correct");
+ equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct");
+ equal(msg.result[0].exists, true, "download.exists is correct");
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "error", "cannot pause a completed download");
+
+ msg = yield runInExtension("resume", id);
+ equal(msg.status, "error", "cannot resume a completed download");
+});
+
+add_task(function* test_pausecancel() {
+ let url = getInterruptibleUrl();
+ let msg = yield runInExtension("download", {url});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ let progressPromise = waitForProgress(url, INT_PARTIAL_LEN);
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id}},
+ ]);
+ equal(msg.status, "success", "got created and changed events");
+
+ yield progressPromise;
+ do_print(`download reached ${INT_PARTIAL_LEN} bytes`);
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "success", "pause() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "interrupted",
+ },
+ paused: {
+ previous: false,
+ current: true,
+ },
+ canResume: {
+ previous: false,
+ current: true,
+ },
+ },
+ }, {
+ type: "onChanged",
+ data: {
+ id,
+ error: {
+ previous: null,
+ current: "USER_CANCELED",
+ },
+ },
+ }]);
+ equal(msg.status, "success", "got onChanged event corresponding to pause");
+
+ msg = yield runInExtension("search", {paused: true});
+ equal(msg.status, "success", "search() succeeded");
+ equal(msg.result.length, 1, "search() found 1 download");
+ equal(msg.result[0].id, id, "download.id is correct");
+ equal(msg.result[0].state, "interrupted", "download.state is correct");
+ equal(msg.result[0].paused, true, "download.paused is correct");
+ equal(msg.result[0].canResume, true, "download.canResume is correct");
+ equal(msg.result[0].error, "USER_CANCELED", "download.error is correct");
+ equal(msg.result[0].bytesReceived, INT_PARTIAL_LEN, "download.bytesReceived is correct");
+ equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct");
+ equal(msg.result[0].exists, false, "download.exists is correct");
+
+ msg = yield runInExtension("search", {error: "USER_CANCELED"});
+ equal(msg.status, "success", "search() succeeded");
+ let found = msg.result.filter(item => item.id == id);
+ equal(found.length, 1, "search() by error found the paused download");
+
+ msg = yield runInExtension("cancel", id);
+ equal(msg.status, "success", "cancel() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ paused: {
+ previous: true,
+ current: false,
+ },
+ canResume: {
+ previous: true,
+ current: false,
+ },
+ },
+ },
+ ]);
+ equal(msg.status, "success", "got onChanged event for cancel");
+
+ msg = yield runInExtension("search", {id});
+ equal(msg.status, "success", "search() succeeded");
+ equal(msg.result.length, 1, "search() found 1 download");
+ equal(msg.result[0].state, "interrupted", "download.state is correct");
+ equal(msg.result[0].paused, false, "download.paused is correct");
+ equal(msg.result[0].canResume, false, "download.canResume is correct");
+ equal(msg.result[0].error, "USER_CANCELED", "download.error is correct");
+ equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct");
+ equal(msg.result[0].exists, false, "download.exists is correct");
+});
+
+add_task(function* test_pause_resume_cancel_badargs() {
+ let BAD_ID = 1000;
+
+ let msg = yield runInExtension("pause", BAD_ID);
+ equal(msg.status, "error", "pause() failed with a bad download id");
+ ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive");
+
+ msg = yield runInExtension("resume", BAD_ID);
+ equal(msg.status, "error", "resume() failed with a bad download id");
+ ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive");
+
+ msg = yield runInExtension("cancel", BAD_ID);
+ equal(msg.status, "error", "cancel() failed with a bad download id");
+ ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive");
+});
+
+add_task(function* test_file_removal() {
+ let msg = yield runInExtension("download", {url: TXT_URL});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id, url: TXT_URL}},
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "complete",
+ },
+ },
+ },
+ ]);
+
+ equal(msg.status, "success", "got onCreated and onChanged events");
+
+ msg = yield runInExtension("removeFile", id);
+ equal(msg.status, "success", "removeFile() succeeded");
+
+ msg = yield runInExtension("removeFile", id);
+ equal(msg.status, "error", "removeFile() fails since the file was already removed.");
+ ok(/file doesn't exist/.test(msg.errmsg), "removeFile() failed on removed file.");
+
+ msg = yield runInExtension("removeFile", 1000);
+ ok(/Invalid download id/.test(msg.errmsg), "removeFile() failed due to non-existent id");
+});
+
+add_task(function* test_removal_of_incomplete_download() {
+ let url = getInterruptibleUrl();
+ let msg = yield runInExtension("download", {url});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ let progressPromise = waitForProgress(url, INT_PARTIAL_LEN);
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id}},
+ ]);
+ equal(msg.status, "success", "got created and changed events");
+
+ yield progressPromise;
+ do_print(`download reached ${INT_PARTIAL_LEN} bytes`);
+
+ msg = yield runInExtension("pause", id);
+ equal(msg.status, "success", "pause() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "interrupted",
+ },
+ paused: {
+ previous: false,
+ current: true,
+ },
+ canResume: {
+ previous: false,
+ current: true,
+ },
+ },
+ }, {
+ type: "onChanged",
+ data: {
+ id,
+ error: {
+ previous: null,
+ current: "USER_CANCELED",
+ },
+ },
+ }]);
+ equal(msg.status, "success", "got onChanged event corresponding to pause");
+
+ msg = yield runInExtension("removeFile", id);
+ equal(msg.status, "error", "removeFile() on paused download failed");
+
+ ok(/Cannot remove incomplete download/.test(msg.errmsg), "removeFile() failed due to download being incomplete");
+
+ msg = yield runInExtension("resume", id);
+ equal(msg.status, "success", "resume() succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "interrupted",
+ current: "in_progress",
+ },
+ paused: {
+ previous: true,
+ current: false,
+ },
+ canResume: {
+ previous: true,
+ current: false,
+ },
+ error: {
+ previous: "USER_CANCELED",
+ current: null,
+ },
+ },
+ },
+ {
+ type: "onChanged",
+ data: {
+ id,
+ state: {
+ previous: "in_progress",
+ current: "complete",
+ },
+ },
+ },
+ ]);
+ equal(msg.status, "success", "got onChanged events for resume and complete");
+
+ msg = yield runInExtension("removeFile", id);
+ equal(msg.status, "success", "removeFile() succeeded following completion of resumed download.");
+});
+
+// Test erase(). We don't do elaborate testing of the query handling
+// since it uses the exact same engine as search() which is tested
+// more thoroughly in test_chrome_ext_downloads_search.html
+add_task(function* test_erase() {
+ yield clearDownloads();
+
+ yield runInExtension("clearEvents");
+
+ function* download() {
+ let msg = yield runInExtension("download", {url: TXT_URL});
+ equal(msg.status, "success", "download succeeded");
+ let id = msg.result;
+
+ msg = yield runInExtension("waitForEvents", [{
+ type: "onChanged", data: {id, state: {current: "complete"}},
+ }], {exact: false});
+ equal(msg.status, "success", "download finished");
+
+ return id;
+ }
+
+ let ids = {};
+ ids.dl1 = yield download();
+ ids.dl2 = yield download();
+ ids.dl3 = yield download();
+
+ let msg = yield runInExtension("search", {});
+ equal(msg.status, "success", "search succeded");
+ equal(msg.result.length, 3, "search found 3 downloads");
+
+ msg = yield runInExtension("clearEvents");
+
+ msg = yield runInExtension("erase", {id: ids.dl1});
+ equal(msg.status, "success", "erase by id succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onErased", data: ids.dl1},
+ ]);
+ equal(msg.status, "success", "received onErased event");
+
+ msg = yield runInExtension("search", {});
+ equal(msg.status, "success", "search succeded");
+ equal(msg.result.length, 2, "search found 2 downloads");
+
+ msg = yield runInExtension("erase", {});
+ equal(msg.status, "success", "erase everything succeeded");
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onErased", data: ids.dl2},
+ {type: "onErased", data: ids.dl3},
+ ], {inorder: false});
+ equal(msg.status, "success", "received 2 onErased events");
+
+ msg = yield runInExtension("search", {});
+ equal(msg.status, "success", "search succeded");
+ equal(msg.result.length, 0, "search found 0 downloads");
+});
+
+function loadImage(img, data) {
+ return new Promise((resolve) => {
+ img.src = data;
+ img.onload = resolve;
+ });
+}
+
+add_task(function* test_getFileIcon() {
+ let webNav = Services.appShell.createWindowlessBrowser(false);
+ let docShell = webNav.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDocShell);
+
+ let system = Services.scriptSecurityManager.getSystemPrincipal();
+ docShell.createAboutBlankContentViewer(system);
+
+ let img = webNav.document.createElement("img");
+
+ let msg = yield runInExtension("download", {url: TXT_URL});
+ equal(msg.status, "success", "download() succeeded");
+ const id = msg.result;
+
+ msg = yield runInExtension("getFileIcon", id);
+ equal(msg.status, "success", "getFileIcon() succeeded");
+ yield loadImage(img, msg.result);
+ equal(img.height, 32, "returns an icon with the right height");
+ equal(img.width, 32, "returns an icon with the right width");
+
+ msg = yield runInExtension("waitForEvents", [
+ {type: "onCreated", data: {id, url: TXT_URL}},
+ {type: "onChanged"},
+ ]);
+ equal(msg.status, "success", "got events");
+
+ msg = yield runInExtension("getFileIcon", id);
+ equal(msg.status, "success", "getFileIcon() succeeded");
+ yield loadImage(img, msg.result);
+ equal(img.height, 32, "returns an icon with the right height after download");
+ equal(img.width, 32, "returns an icon with the right width after download");
+
+ msg = yield runInExtension("getFileIcon", id + 100);
+ equal(msg.status, "error", "getFileIcon() failed");
+ ok(msg.errmsg.includes("Invalid download id"), "download id is invalid");
+
+ msg = yield runInExtension("getFileIcon", id, {size: 127});
+ equal(msg.status, "success", "getFileIcon() succeeded");
+ yield loadImage(img, msg.result);
+ equal(img.height, 127, "returns an icon with the right custom height");
+ equal(img.width, 127, "returns an icon with the right custom width");
+
+ msg = yield runInExtension("getFileIcon", id, {size: 1});
+ equal(msg.status, "success", "getFileIcon() succeeded");
+ yield loadImage(img, msg.result);
+ equal(img.height, 1, "returns an icon with the right custom height");
+ equal(img.width, 1, "returns an icon with the right custom width");
+
+ msg = yield runInExtension("getFileIcon", id, {size: "foo"});
+ equal(msg.status, "error", "getFileIcon() fails");
+ ok(msg.errmsg.includes("Error processing size"), "size is not a number");
+
+ msg = yield runInExtension("getFileIcon", id, {size: 0});
+ equal(msg.status, "error", "getFileIcon() fails");
+ ok(msg.errmsg.includes("Error processing size"), "size is too small");
+
+ msg = yield runInExtension("getFileIcon", id, {size: 128});
+ equal(msg.status, "error", "getFileIcon() fails");
+ ok(msg.errmsg.includes("Error processing size"), "size is too big");
+
+ webNav.close();
+});
+
+add_task(function* cleanup() {
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js
new file mode 100644
index 000000000..4caa82456
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js
@@ -0,0 +1,402 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://gre/modules/Downloads.jsm");
+
+const server = createHttpServer();
+server.registerDirectory("/data/", do_get_file("data"));
+
+const BASE = `http://localhost:${server.identity.primaryPort}/data`;
+const TXT_FILE = "file_download.txt";
+const TXT_URL = BASE + "/" + TXT_FILE;
+const TXT_LEN = 46;
+const HTML_FILE = "file_download.html";
+const HTML_URL = BASE + "/" + HTML_FILE;
+const HTML_LEN = 117;
+const BIG_LEN = 1000; // something bigger both TXT_LEN and HTML_LEN
+
+function backgroundScript() {
+ let complete = new Map();
+
+ function waitForComplete(id) {
+ if (complete.has(id)) {
+ return complete.get(id).promise;
+ }
+
+ let promise = new Promise(resolve => {
+ complete.set(id, {resolve});
+ });
+ complete.get(id).promise = promise;
+ return promise;
+ }
+
+ browser.downloads.onChanged.addListener(change => {
+ if (change.state && change.state.current == "complete") {
+ // Make sure we have a promise.
+ waitForComplete(change.id);
+ complete.get(change.id).resolve();
+ }
+ });
+
+ browser.test.onMessage.addListener(async (msg, ...args) => {
+ if (msg == "download.request") {
+ try {
+ let id = await browser.downloads.download(args[0]);
+ browser.test.sendMessage("download.done", {status: "success", id});
+ } catch (error) {
+ browser.test.sendMessage("download.done", {status: "error", errmsg: error.message});
+ }
+ } else if (msg == "search.request") {
+ try {
+ let downloads = await browser.downloads.search(args[0]);
+ browser.test.sendMessage("search.done", {status: "success", downloads});
+ } catch (error) {
+ browser.test.sendMessage("search.done", {status: "error", errmsg: error.message});
+ }
+ } else if (msg == "waitForComplete.request") {
+ await waitForComplete(args[0]);
+ browser.test.sendMessage("waitForComplete.done");
+ }
+ });
+
+ browser.test.sendMessage("ready");
+}
+
+async function clearDownloads(callback) {
+ let list = await Downloads.getList(Downloads.ALL);
+ let downloads = await list.getAll();
+
+ await Promise.all(downloads.map(download => list.remove(download)));
+
+ return downloads;
+}
+
+add_task(function* test_search() {
+ const nsIFile = Ci.nsIFile;
+ let downloadDir = FileUtils.getDir("TmpD", ["downloads"]);
+ downloadDir.createUnique(nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+ do_print(`downloadDir ${downloadDir.path}`);
+
+ function downloadPath(filename) {
+ let path = downloadDir.clone();
+ path.append(filename);
+ return path.path;
+ }
+
+ Services.prefs.setIntPref("browser.download.folderList", 2);
+ Services.prefs.setComplexValue("browser.download.dir", nsIFile, downloadDir);
+
+ do_register_cleanup(async () => {
+ Services.prefs.clearUserPref("browser.download.folderList");
+ Services.prefs.clearUserPref("browser.download.dir");
+ await cleanupDir(downloadDir);
+ await clearDownloads();
+ });
+
+ yield clearDownloads().then(downloads => {
+ do_print(`removed ${downloads.length} pre-existing downloads from history`);
+ });
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background: backgroundScript,
+ manifest: {
+ permissions: ["downloads"],
+ },
+ });
+
+ async function download(options) {
+ extension.sendMessage("download.request", options);
+ let result = await extension.awaitMessage("download.done");
+
+ if (result.status == "success") {
+ do_print(`wait for onChanged event to indicate ${result.id} is complete`);
+ extension.sendMessage("waitForComplete.request", result.id);
+
+ await extension.awaitMessage("waitForComplete.done");
+ }
+
+ return result;
+ }
+
+ function search(query) {
+ extension.sendMessage("search.request", query);
+ return extension.awaitMessage("search.done");
+ }
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ // Do some downloads...
+ const time1 = new Date();
+
+ let downloadIds = {};
+ let msg = yield download({url: TXT_URL});
+ equal(msg.status, "success", "download() succeeded");
+ downloadIds.txt1 = msg.id;
+
+ const TXT_FILE2 = "NewFile.txt";
+ msg = yield download({url: TXT_URL, filename: TXT_FILE2});
+ equal(msg.status, "success", "download() succeeded");
+ downloadIds.txt2 = msg.id;
+
+ const time2 = new Date();
+
+ msg = yield download({url: HTML_URL});
+ equal(msg.status, "success", "download() succeeded");
+ downloadIds.html1 = msg.id;
+
+ const HTML_FILE2 = "renamed.html";
+ msg = yield download({url: HTML_URL, filename: HTML_FILE2});
+ equal(msg.status, "success", "download() succeeded");
+ downloadIds.html2 = msg.id;
+
+ const time3 = new Date();
+
+ // Search for each individual download and check
+ // the corresponding DownloadItem.
+ function* checkDownloadItem(id, expect) {
+ let item = yield search({id});
+ equal(item.status, "success", "search() succeeded");
+ equal(item.downloads.length, 1, "search() found exactly 1 download");
+
+ Object.keys(expect).forEach(function(field) {
+ equal(item.downloads[0][field], expect[field], `DownloadItem.${field} is correct"`);
+ });
+ }
+ yield checkDownloadItem(downloadIds.txt1, {
+ url: TXT_URL,
+ filename: downloadPath(TXT_FILE),
+ mime: "text/plain",
+ state: "complete",
+ bytesReceived: TXT_LEN,
+ totalBytes: TXT_LEN,
+ fileSize: TXT_LEN,
+ exists: true,
+ });
+
+ yield checkDownloadItem(downloadIds.txt2, {
+ url: TXT_URL,
+ filename: downloadPath(TXT_FILE2),
+ mime: "text/plain",
+ state: "complete",
+ bytesReceived: TXT_LEN,
+ totalBytes: TXT_LEN,
+ fileSize: TXT_LEN,
+ exists: true,
+ });
+
+ yield checkDownloadItem(downloadIds.html1, {
+ url: HTML_URL,
+ filename: downloadPath(HTML_FILE),
+ mime: "text/html",
+ state: "complete",
+ bytesReceived: HTML_LEN,
+ totalBytes: HTML_LEN,
+ fileSize: HTML_LEN,
+ exists: true,
+ });
+
+ yield checkDownloadItem(downloadIds.html2, {
+ url: HTML_URL,
+ filename: downloadPath(HTML_FILE2),
+ mime: "text/html",
+ state: "complete",
+ bytesReceived: HTML_LEN,
+ totalBytes: HTML_LEN,
+ fileSize: HTML_LEN,
+ exists: true,
+ });
+
+ function* checkSearch(query, expected, description, exact) {
+ let item = yield search(query);
+ equal(item.status, "success", "search() succeeded");
+ equal(item.downloads.length, expected.length, `search() for ${description} found exactly ${expected.length} downloads`);
+
+ let receivedIds = item.downloads.map(i => i.id);
+ if (exact) {
+ receivedIds.forEach((id, idx) => {
+ equal(id, downloadIds[expected[idx]], `search() for ${description} returned ${expected[idx]} in position ${idx}`);
+ });
+ } else {
+ Object.keys(downloadIds).forEach(key => {
+ const id = downloadIds[key];
+ const thisExpected = expected.includes(key);
+ equal(receivedIds.includes(id), thisExpected,
+ `search() for ${description} ${thisExpected ? "includes" : "does not include"} ${key}`);
+ });
+ }
+ }
+
+ // Check that search with an invalid id returns nothing.
+ // NB: for now ids are not persistent and we start numbering them at 1
+ // so a sufficiently large number will be unused.
+ const INVALID_ID = 1000;
+ yield checkSearch({id: INVALID_ID}, [], "invalid id");
+
+ // Check that search on url works.
+ yield checkSearch({url: TXT_URL}, ["txt1", "txt2"], "url");
+
+ // Check that regexp on url works.
+ const HTML_REGEX = "[downlad]{8}\.html+$";
+ yield checkSearch({urlRegex: HTML_REGEX}, ["html1", "html2"], "url regexp");
+
+ // Check that compatible url+regexp works
+ yield checkSearch({url: HTML_URL, urlRegex: HTML_REGEX}, ["html1", "html2"], "compatible url+urlRegex");
+
+ // Check that incompatible url+regexp works
+ yield checkSearch({url: TXT_URL, urlRegex: HTML_REGEX}, [], "incompatible url+urlRegex");
+
+ // Check that search on filename works.
+ yield checkSearch({filename: downloadPath(TXT_FILE)}, ["txt1"], "filename");
+
+ // Check that regexp on filename works.
+ yield checkSearch({filenameRegex: HTML_REGEX}, ["html1"], "filename regex");
+
+ // Check that compatible filename+regexp works
+ yield checkSearch({filename: downloadPath(HTML_FILE), filenameRegex: HTML_REGEX}, ["html1"], "compatible filename+filename regex");
+
+ // Check that incompatible filename+regexp works
+ yield checkSearch({filename: downloadPath(TXT_FILE), filenameRegex: HTML_REGEX}, [], "incompatible filename+filename regex");
+
+ // Check that simple positive search terms work.
+ yield checkSearch({query: ["file_download"]}, ["txt1", "txt2", "html1", "html2"],
+ "term file_download");
+ yield checkSearch({query: ["NewFile"]}, ["txt2"], "term NewFile");
+
+ // Check that positive search terms work case-insensitive.
+ yield checkSearch({query: ["nEwfILe"]}, ["txt2"], "term nEwfiLe");
+
+ // Check that negative search terms work.
+ yield checkSearch({query: ["-txt"]}, ["html1", "html2"], "term -txt");
+
+ // Check that positive and negative search terms together work.
+ yield checkSearch({query: ["html", "-renamed"]}, ["html1"], "postive and negative terms");
+
+ function* checkSearchWithDate(query, expected, description) {
+ const fields = Object.keys(query);
+ if (fields.length != 1 || !(query[fields[0]] instanceof Date)) {
+ throw new Error("checkSearchWithDate expects exactly one Date field");
+ }
+ const field = fields[0];
+ const date = query[field];
+
+ let newquery = {};
+
+ // Check as a Date
+ newquery[field] = date;
+ yield checkSearch(newquery, expected, `${description} as Date`);
+
+ // Check as numeric milliseconds
+ newquery[field] = date.valueOf();
+ yield checkSearch(newquery, expected, `${description} as numeric ms`);
+
+ // Check as stringified milliseconds
+ newquery[field] = date.valueOf().toString();
+ yield checkSearch(newquery, expected, `${description} as string ms`);
+
+ // Check as ISO string
+ newquery[field] = date.toISOString();
+ yield checkSearch(newquery, expected, `${description} as iso string`);
+ }
+
+ // Check startedBefore
+ yield checkSearchWithDate({startedBefore: time1}, [], "before time1");
+ yield checkSearchWithDate({startedBefore: time2}, ["txt1", "txt2"], "before time2");
+ yield checkSearchWithDate({startedBefore: time3}, ["txt1", "txt2", "html1", "html2"], "before time3");
+
+ // Check startedAfter
+ yield checkSearchWithDate({startedAfter: time1}, ["txt1", "txt2", "html1", "html2"], "after time1");
+ yield checkSearchWithDate({startedAfter: time2}, ["html1", "html2"], "after time2");
+ yield checkSearchWithDate({startedAfter: time3}, [], "after time3");
+
+ // Check simple search on totalBytes
+ yield checkSearch({totalBytes: TXT_LEN}, ["txt1", "txt2"], "totalBytes");
+ yield checkSearch({totalBytes: HTML_LEN}, ["html1", "html2"], "totalBytes");
+
+ // Check simple test on totalBytes{Greater,Less}
+ // (NB: TXT_LEN < HTML_LEN < BIG_LEN)
+ yield checkSearch({totalBytesGreater: 0}, ["txt1", "txt2", "html1", "html2"], "totalBytesGreater than 0");
+ yield checkSearch({totalBytesGreater: TXT_LEN}, ["html1", "html2"], `totalBytesGreater than ${TXT_LEN}`);
+ yield checkSearch({totalBytesGreater: HTML_LEN}, [], `totalBytesGreater than ${HTML_LEN}`);
+ yield checkSearch({totalBytesLess: TXT_LEN}, [], `totalBytesLess than ${TXT_LEN}`);
+ yield checkSearch({totalBytesLess: HTML_LEN}, ["txt1", "txt2"], `totalBytesLess than ${HTML_LEN}`);
+ yield checkSearch({totalBytesLess: BIG_LEN}, ["txt1", "txt2", "html1", "html2"], `totalBytesLess than ${BIG_LEN}`);
+
+ // Check good combinations of totalBytes*.
+ yield checkSearch({totalBytes: HTML_LEN, totalBytesGreater: TXT_LEN}, ["html1", "html2"], "totalBytes and totalBytesGreater");
+ yield checkSearch({totalBytes: TXT_LEN, totalBytesLess: HTML_LEN}, ["txt1", "txt2"], "totalBytes and totalBytesGreater");
+ yield checkSearch({totalBytes: HTML_LEN, totalBytesLess: BIG_LEN, totalBytesGreater: 0}, ["html1", "html2"], "totalBytes and totalBytesLess and totalBytesGreater");
+
+ // Check bad combination of totalBytes*.
+ yield checkSearch({totalBytesLess: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytesLess, totalBytesGreater combination");
+ yield checkSearch({totalBytes: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytes, totalBytesGreater combination");
+ yield checkSearch({totalBytes: HTML_LEN, totalBytesLess: TXT_LEN}, [], "bad totalBytes, totalBytesLess combination");
+
+ // Check mime.
+ yield checkSearch({mime: "text/plain"}, ["txt1", "txt2"], "mime text/plain");
+ yield checkSearch({mime: "text/html"}, ["html1", "html2"], "mime text/htmlplain");
+ yield checkSearch({mime: "video/webm"}, [], "mime video/webm");
+
+ // Check fileSize.
+ yield checkSearch({fileSize: TXT_LEN}, ["txt1", "txt2"], "fileSize");
+ yield checkSearch({fileSize: HTML_LEN}, ["html1", "html2"], "fileSize");
+
+ // Fields like bytesReceived, paused, state, exists are meaningful
+ // for downloads that are in progress but have not yet completed.
+ // todo: add tests for these when we have better support for in-progress
+ // downloads (e.g., after pause(), resume() and cancel() are implemented)
+
+ // Check multiple query properties.
+ // We could make this testing arbitrarily complicated...
+ // We already tested combining fields with obvious interactions above
+ // (e.g., filename and filenameRegex or startTime and startedBefore/After)
+ // so now just throw as many fields as we can at a single search and
+ // make sure a simple case still works.
+ yield checkSearch({
+ url: TXT_URL,
+ urlRegex: "download",
+ filename: downloadPath(TXT_FILE),
+ filenameRegex: "download",
+ query: ["download"],
+ startedAfter: time1.valueOf().toString(),
+ startedBefore: time2.valueOf().toString(),
+ totalBytes: TXT_LEN,
+ totalBytesGreater: 0,
+ totalBytesLess: BIG_LEN,
+ mime: "text/plain",
+ fileSize: TXT_LEN,
+ }, ["txt1"], "many properties");
+
+ // Check simple orderBy (forward and backward).
+ yield checkSearch({orderBy: ["startTime"]}, ["txt1", "txt2", "html1", "html2"], "orderBy startTime", true);
+ yield checkSearch({orderBy: ["-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy -startTime", true);
+
+ // Check orderBy with multiple fields.
+ // NB: TXT_URL and HTML_URL differ only in extension and .html precedes .txt
+ yield checkSearch({orderBy: ["url", "-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy with multiple fields", true);
+
+ // Check orderBy with limit.
+ yield checkSearch({orderBy: ["url"], limit: 1}, ["html1"], "orderBy with limit", true);
+
+ // Check bad arguments.
+ function* checkBadSearch(query, pattern, description) {
+ let item = yield search(query);
+ equal(item.status, "error", "search() failed");
+ ok(pattern.test(item.errmsg), `error message for ${description} was correct (${item.errmsg}).`);
+ }
+
+ yield checkBadSearch("myquery", /Incorrect argument type/, "query is not an object");
+ yield checkBadSearch({bogus: "boo"}, /Unexpected property/, "query contains an unknown field");
+ yield checkBadSearch({query: "query string"}, /Expected array/, "query.query is a string");
+ yield checkBadSearch({startedBefore: "i am not a time"}, /Type error/, "query.startedBefore is not a valid time");
+ yield checkBadSearch({startedAfter: "i am not a time"}, /Type error/, "query.startedAfter is not a valid time");
+ yield checkBadSearch({endedBefore: "i am not a time"}, /Type error/, "query.endedBefore is not a valid time");
+ yield checkBadSearch({endedAfter: "i am not a time"}, /Type error/, "query.endedAfter is not a valid time");
+ yield checkBadSearch({urlRegex: "["}, /Invalid urlRegex/, "query.urlRegexp is not a valid regular expression");
+ yield checkBadSearch({filenameRegex: "["}, /Invalid filenameRegex/, "query.filenameRegexp is not a valid regular expression");
+ yield checkBadSearch({orderBy: "startTime"}, /Expected array/, "query.orderBy is not an array");
+ yield checkBadSearch({orderBy: ["bogus"]}, /Invalid orderBy field/, "query.orderBy references a non-existent field");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js b/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js
new file mode 100644
index 000000000..bc6bfcd68
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js
@@ -0,0 +1,175 @@
+"use strict";
+
+/* globals browser */
+
+XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
+ "resource://gre/modules/AddonManager.jsm");
+
+function promiseAddonStartup() {
+ const {Management} = Cu.import("resource://gre/modules/Extension.jsm");
+
+ return new Promise(resolve => {
+ let listener = (evt, extension) => {
+ Management.off("startup", listener);
+ resolve(extension);
+ };
+
+ Management.on("startup", listener);
+ });
+}
+
+add_task(function* setup() {
+ yield ExtensionTestUtils.startAddonManager();
+});
+
+add_task(function* test_experiments_api() {
+ let apiAddonFile = Extension.generateZipFile({
+ "install.rdf": `<?xml version="1.0" encoding="UTF-8"?>
+ <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+ <Description about="urn:mozilla:install-manifest"
+ em:id="meh@experiments.addons.mozilla.org"
+ em:name="Meh Experiment"
+ em:type="256"
+ em:version="0.1"
+ em:description="Meh experiment"
+ em:creator="Mozilla">
+
+ <em:targetApplication>
+ <Description
+ em:id="xpcshell@tests.mozilla.org"
+ em:minVersion="48"
+ em:maxVersion="*"/>
+ </em:targetApplication>
+ </Description>
+ </RDF>
+ `,
+
+ "api.js": String.raw`
+ Components.utils.import("resource://gre/modules/Services.jsm");
+
+ Services.obs.notifyObservers(null, "webext-api-loaded", "");
+
+ class API extends ExtensionAPI {
+ getAPI(context) {
+ return {
+ meh: {
+ hello(text) {
+ Services.obs.notifyObservers(null, "webext-api-hello", text);
+ }
+ }
+ }
+ }
+ }
+ `,
+
+ "schema.json": [
+ {
+ "namespace": "meh",
+ "description": "All full of meh.",
+ "permissions": ["experiments.meh"],
+ "functions": [
+ {
+ "name": "hello",
+ "type": "function",
+ "description": "Hates you. This is all.",
+ "parameters": [
+ {"type": "string", "name": "text"},
+ ],
+ },
+ ],
+ },
+ ],
+ });
+
+ let addonFile = Extension.generateXPI({
+ manifest: {
+ applications: {gecko: {id: "meh@web.extension"}},
+ permissions: ["experiments.meh"],
+ },
+
+ background() {
+ // The test code below checks that hello() is called at the right
+ // time with the string "Here I am". Verify that the api schema is
+ // being correctly interpreted by calling hello() with bad arguments
+ // and only calling hello() with the magic string if the call with
+ // bad arguments throws.
+ try {
+ browser.meh.hello("I should not see this", "since two arguments are bad");
+ } catch (err) {
+ browser.meh.hello("Here I am");
+ }
+ },
+ });
+
+ let boringAddonFile = Extension.generateXPI({
+ manifest: {
+ applications: {gecko: {id: "boring@web.extension"}},
+ },
+ background() {
+ if (browser.meh) {
+ browser.meh.hello("Here I should not be");
+ }
+ },
+ });
+
+ do_register_cleanup(() => {
+ for (let file of [apiAddonFile, addonFile, boringAddonFile]) {
+ Services.obs.notifyObservers(file, "flush-cache-entry", null);
+ file.remove(false);
+ }
+ });
+
+
+ let resolveHello;
+ let observer = (subject, topic, data) => {
+ if (topic == "webext-api-loaded") {
+ ok(!!resolveHello, "Should not see API loaded until dependent extension loads");
+ } else if (topic == "webext-api-hello") {
+ resolveHello(data);
+ }
+ };
+
+ Services.obs.addObserver(observer, "webext-api-loaded", false);
+ Services.obs.addObserver(observer, "webext-api-hello", false);
+ do_register_cleanup(() => {
+ Services.obs.removeObserver(observer, "webext-api-loaded");
+ Services.obs.removeObserver(observer, "webext-api-hello");
+ });
+
+
+ // Install API add-on.
+ let apiAddon = yield AddonManager.installTemporaryAddon(apiAddonFile);
+
+ let {APIs} = Cu.import("resource://gre/modules/ExtensionManagement.jsm", {});
+ ok(APIs.apis.has("meh"), "Should have meh API.");
+
+
+ // Install boring WebExtension add-on.
+ let boringAddon = yield AddonManager.installTemporaryAddon(boringAddonFile);
+ yield promiseAddonStartup();
+
+
+ // Install interesting WebExtension add-on.
+ let promise = new Promise(resolve => {
+ resolveHello = resolve;
+ });
+
+ let addon = yield AddonManager.installTemporaryAddon(addonFile);
+ yield promiseAddonStartup();
+
+ let hello = yield promise;
+ equal(hello, "Here I am", "Should get hello from add-on");
+
+ // Cleanup.
+ apiAddon.uninstall();
+
+ boringAddon.userDisabled = true;
+ yield new Promise(do_execute_soon);
+
+ equal(addon.appDisabled, true, "Add-on should be app-disabled after its dependency is removed.");
+
+ addon.uninstall();
+ boringAddon.uninstall();
+});
+
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js b/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js
new file mode 100644
index 000000000..f18845f6a
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js
@@ -0,0 +1,55 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_is_allowed_incognito_access() {
+ async function background() {
+ let allowed = await browser.extension.isAllowedIncognitoAccess();
+
+ browser.test.assertEq(true, allowed, "isAllowedIncognitoAccess is true");
+ browser.test.notifyPass("isAllowedIncognitoAccess");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {},
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("isAllowedIncognitoAccess");
+ yield extension.unload();
+});
+
+add_task(function* test_in_incognito_context_false() {
+ function background() {
+ browser.test.assertEq(false, browser.extension.inIncognitoContext, "inIncognitoContext returned false");
+ browser.test.notifyPass("inIncognitoContext");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {},
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("inIncognitoContext");
+ yield extension.unload();
+});
+
+add_task(function* test_is_allowed_file_scheme_access() {
+ async function background() {
+ let allowed = await browser.extension.isAllowedFileSchemeAccess();
+
+ browser.test.assertEq(false, allowed, "isAllowedFileSchemeAccess is false");
+ browser.test.notifyPass("isAllowedFileSchemeAccess");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {},
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("isAllowedFileSchemeAccess");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js b/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js
new file mode 100644
index 000000000..89bcac217
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js
@@ -0,0 +1,202 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://testing-common/MockRegistrar.jsm");
+
+let idleService = {
+ _observers: new Set(),
+ _activity: {
+ addCalls: [],
+ removeCalls: [],
+ observerFires: [],
+ },
+ _reset: function() {
+ this._observers.clear();
+ this._activity.addCalls = [];
+ this._activity.removeCalls = [];
+ this._activity.observerFires = [];
+ },
+ _fireObservers: function(state) {
+ for (let observer of this._observers.values()) {
+ observer.observe(observer, state, null);
+ this._activity.observerFires.push(state);
+ }
+ },
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIIdleService]),
+ idleTime: 19999,
+ addIdleObserver: function(observer, time) {
+ this._observers.add(observer);
+ this._activity.addCalls.push(time);
+ },
+ removeIdleObserver: function(observer, time) {
+ this._observers.delete(observer);
+ this._activity.removeCalls.push(time);
+ },
+};
+
+function checkActivity(expectedActivity) {
+ let {expectedAdd, expectedRemove, expectedFires} = expectedActivity;
+ let {addCalls, removeCalls, observerFires} = idleService._activity;
+ equal(expectedAdd.length, addCalls.length, "idleService.addIdleObserver was called the expected number of times");
+ equal(expectedRemove.length, removeCalls.length, "idleService.removeIdleObserver was called the expected number of times");
+ equal(expectedFires.length, observerFires.length, "idle observer was fired the expected number of times");
+ deepEqual(addCalls, expectedAdd, "expected interval passed to idleService.addIdleObserver");
+ deepEqual(removeCalls, expectedRemove, "expected interval passed to idleService.removeIdleObserver");
+ deepEqual(observerFires, expectedFires, "expected topic passed to idle observer");
+}
+
+add_task(function* setup() {
+ let fakeIdleService = MockRegistrar.register("@mozilla.org/widget/idleservice;1", idleService);
+ do_register_cleanup(() => {
+ MockRegistrar.unregister(fakeIdleService);
+ });
+});
+
+add_task(function* testQueryStateActive() {
+ function background() {
+ browser.idle.queryState(20).then(status => {
+ browser.test.assertEq("active", status, "Idle status is active");
+ browser.test.notifyPass("idle");
+ },
+ err => {
+ browser.test.fail(`Error: ${err} :: ${err.stack}`);
+ browser.test.notifyFail("idle");
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("idle");
+ yield extension.unload();
+});
+
+add_task(function* testQueryStateIdle() {
+ function background() {
+ browser.idle.queryState(15).then(status => {
+ browser.test.assertEq("idle", status, "Idle status is idle");
+ browser.test.notifyPass("idle");
+ },
+ err => {
+ browser.test.fail(`Error: ${err} :: ${err.stack}`);
+ browser.test.notifyFail("idle");
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("idle");
+ yield extension.unload();
+});
+
+add_task(function* testOnlySetDetectionInterval() {
+ function background() {
+ browser.idle.setDetectionInterval(99);
+ browser.test.sendMessage("detectionIntervalSet");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ idleService._reset();
+ yield extension.startup();
+ yield extension.awaitMessage("detectionIntervalSet");
+ idleService._fireObservers("idle");
+ checkActivity({expectedAdd: [], expectedRemove: [], expectedFires: []});
+ yield extension.unload();
+});
+
+add_task(function* testSetDetectionIntervalBeforeAddingListener() {
+ function background() {
+ browser.idle.setDetectionInterval(99);
+ browser.idle.onStateChanged.addListener(newState => {
+ browser.test.assertEq("idle", newState, "listener fired with the expected state");
+ browser.test.sendMessage("listenerFired");
+ });
+ browser.test.sendMessage("listenerAdded");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ idleService._reset();
+ yield extension.startup();
+ yield extension.awaitMessage("listenerAdded");
+ idleService._fireObservers("idle");
+ yield extension.awaitMessage("listenerFired");
+ checkActivity({expectedAdd: [99], expectedRemove: [], expectedFires: ["idle"]});
+ yield extension.unload();
+});
+
+add_task(function* testSetDetectionIntervalAfterAddingListener() {
+ function background() {
+ browser.idle.onStateChanged.addListener(newState => {
+ browser.test.assertEq("idle", newState, "listener fired with the expected state");
+ browser.test.sendMessage("listenerFired");
+ });
+ browser.idle.setDetectionInterval(99);
+ browser.test.sendMessage("detectionIntervalSet");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ idleService._reset();
+ yield extension.startup();
+ yield extension.awaitMessage("detectionIntervalSet");
+ idleService._fireObservers("idle");
+ yield extension.awaitMessage("listenerFired");
+ checkActivity({expectedAdd: [60, 99], expectedRemove: [60], expectedFires: ["idle"]});
+ yield extension.unload();
+});
+
+add_task(function* testOnlyAddingListener() {
+ function background() {
+ browser.idle.onStateChanged.addListener(newState => {
+ browser.test.assertEq("active", newState, "listener fired with the expected state");
+ browser.test.sendMessage("listenerFired");
+ });
+ browser.test.sendMessage("listenerAdded");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["idle"],
+ },
+ });
+
+ idleService._reset();
+ yield extension.startup();
+ yield extension.awaitMessage("listenerAdded");
+ idleService._fireObservers("active");
+ yield extension.awaitMessage("listenerFired");
+ // check that "idle-daily" topic does not cause a listener to fire
+ idleService._fireObservers("idle-daily");
+ checkActivity({expectedAdd: [60], expectedRemove: [], expectedFires: ["active", "idle-daily"]});
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js b/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js
new file mode 100644
index 000000000..652f41315
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js
@@ -0,0 +1,37 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_json_parser() {
+ const ID = "json@test.web.extension";
+
+ let xpi = Extension.generateXPI({
+ files: {
+ "manifest.json": String.raw`{
+ // This is a manifest.
+ "applications": {"gecko": {"id": "${ID}"}},
+ "name": "This \" is // not a comment",
+ "version": "0.1\\" // , "description": "This is not a description"
+ }`,
+ },
+ });
+
+ let expectedManifest = {
+ "applications": {"gecko": {"id": ID}},
+ "name": "This \" is // not a comment",
+ "version": "0.1\\",
+ };
+
+ let fileURI = Services.io.newFileURI(xpi);
+ let uri = NetUtil.newURI(`jar:${fileURI.spec}!/`);
+
+ let extension = new ExtensionData(uri);
+
+ yield extension.readManifest();
+
+ Assert.deepEqual(extension.rawManifest, expectedManifest,
+ "Manifest with correctly-filtered comments");
+
+ Services.obs.notifyObservers(xpi, "flush-cache-entry", null);
+ xpi.remove(false);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js
new file mode 100644
index 000000000..63d5361a1
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js
@@ -0,0 +1,168 @@
+"use strict";
+
+/* globals browser */
+
+Cu.import("resource://gre/modules/Extension.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+const {LegacyExtensionContext} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm");
+
+/**
+ * This test case ensures that LegacyExtensionContext instances:
+ * - expose the expected API object and can join the messaging
+ * of a webextension given its addon id
+ * - the exposed API object can receive a port related to a `runtime.connect`
+ * Port created in the webextension's background page
+ * - the received Port instance can exchange messages with the background page
+ * - the received Port receive a disconnect event when the webextension is
+ * shutting down
+ */
+add_task(function* test_legacy_extension_context() {
+ function background() {
+ let bgURL = window.location.href;
+
+ let extensionInfo = {
+ bgURL,
+ // Extract the assigned uuid from the background page url.
+ uuid: window.location.hostname,
+ };
+
+ browser.test.sendMessage("webextension-ready", extensionInfo);
+
+ let port;
+
+ browser.test.onMessage.addListener(async msg => {
+ if (msg == "do-send-message") {
+ let reply = await browser.runtime.sendMessage("webextension -> legacy_extension message");
+
+ browser.test.assertEq("legacy_extension -> webextension reply", reply,
+ "Got the expected message from the LegacyExtensionContext");
+ browser.test.sendMessage("got-reply-message");
+ } else if (msg == "do-connect") {
+ port = browser.runtime.connect();
+
+ port.onMessage.addListener(portMsg => {
+ browser.test.assertEq("legacy_extension -> webextension port message", portMsg,
+ "Got the expected message from the LegacyExtensionContext");
+ port.postMessage("webextension -> legacy_extension port message");
+ });
+ } else if (msg == "do-disconnect") {
+ port.disconnect();
+ }
+ });
+ }
+
+ let extensionData = {
+ background,
+ };
+
+ let extension = Extension.generate(extensionData);
+
+ let waitForExtensionInfo = new Promise((resolve, reject) => {
+ extension.on("test-message", function testMessageListener(kind, msg, ...args) {
+ if (msg != "webextension-ready") {
+ reject(new Error(`Got an unexpected test-message: ${msg}`));
+ } else {
+ extension.off("test-message", testMessageListener);
+ resolve(args[0]);
+ }
+ });
+ });
+
+ // Connect to the target extension as an external context
+ // using the given custom sender info.
+ let legacyContext;
+
+ extension.on("startup", function onStartup() {
+ extension.off("startup", onStartup);
+ legacyContext = new LegacyExtensionContext(extension);
+ extension.callOnClose({
+ close: () => legacyContext.unload(),
+ });
+ });
+
+ yield extension.startup();
+
+ let extensionInfo = yield waitForExtensionInfo;
+
+ equal(legacyContext.envType, "legacy_extension",
+ "LegacyExtensionContext instance has the expected type");
+
+ ok(legacyContext.api, "Got the expected API object");
+ ok(legacyContext.api.browser, "Got the expected browser property");
+
+ let waitMessage = new Promise(resolve => {
+ const {browser} = legacyContext.api;
+ browser.runtime.onMessage.addListener((singleMsg, msgSender) => {
+ resolve({singleMsg, msgSender});
+
+ // Send a reply to the sender.
+ return Promise.resolve("legacy_extension -> webextension reply");
+ });
+ });
+
+ extension.testMessage("do-send-message");
+
+ let {singleMsg, msgSender} = yield waitMessage;
+ equal(singleMsg, "webextension -> legacy_extension message",
+ "Got the expected message");
+ ok(msgSender, "Got a message sender object");
+
+ equal(msgSender.id, extensionInfo.uuid, "The sender has the expected id property");
+ equal(msgSender.url, extensionInfo.bgURL, "The sender has the expected url property");
+
+ // Wait confirmation that the reply has been received.
+ yield new Promise((resolve, reject) => {
+ extension.on("test-message", function testMessageListener(kind, msg, ...args) {
+ if (msg != "got-reply-message") {
+ reject(new Error(`Got an unexpected test-message: ${msg}`));
+ } else {
+ extension.off("test-message", testMessageListener);
+ resolve();
+ }
+ });
+ });
+
+ let waitConnectPort = new Promise(resolve => {
+ let {browser} = legacyContext.api;
+ browser.runtime.onConnect.addListener(port => {
+ resolve(port);
+ });
+ });
+
+ extension.testMessage("do-connect");
+
+ let port = yield waitConnectPort;
+
+ ok(port, "Got the Port API object");
+ ok(port.sender, "The port has a sender property");
+ equal(port.sender.id, extensionInfo.uuid,
+ "The port sender has the expected id property");
+ equal(port.sender.url, extensionInfo.bgURL,
+ "The port sender has the expected url property");
+
+ let waitPortMessage = new Promise(resolve => {
+ port.onMessage.addListener((msg) => {
+ resolve(msg);
+ });
+ });
+
+ port.postMessage("legacy_extension -> webextension port message");
+
+ let msg = yield waitPortMessage;
+
+ equal(msg, "webextension -> legacy_extension port message",
+ "LegacyExtensionContext received the expected message from the webextension");
+
+ let waitForDisconnect = new Promise(resolve => {
+ port.onDisconnect.addListener(resolve);
+ });
+
+ extension.testMessage("do-disconnect");
+
+ yield waitForDisconnect;
+
+ do_print("Got the disconnect event on unload");
+
+ yield extension.shutdown();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js
new file mode 100644
index 000000000..ea5d78524
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js
@@ -0,0 +1,188 @@
+"use strict";
+
+/* globals browser */
+
+Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm");
+
+// Import EmbeddedExtensionManager to be able to check that the
+// tacked instances are cleared after the embedded extension shutdown.
+const {
+ EmbeddedExtensionManager,
+} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {});
+
+/**
+ * This test case ensures that the LegacyExtensionsUtils.EmbeddedExtension:
+ * - load the embedded webextension resources from a "/webextension/" dir
+ * inside the XPI.
+ * - EmbeddedExtension.prototype.api returns an API object which exposes
+ * a working `runtime.onConnect` event object (e.g. the API can receive a port
+ * when the embedded webextension is started and it can exchange messages
+ * with the background page).
+ * - EmbeddedExtension.prototype.startup/shutdown methods manage the embedded
+ * webextension lifecycle as expected.
+ */
+add_task(function* test_embedded_webextension_utils() {
+ function backgroundScript() {
+ let port = browser.runtime.connect();
+
+ port.onMessage.addListener((msg) => {
+ if (msg == "legacy_extension -> webextension") {
+ port.postMessage("webextension -> legacy_extension");
+ port.disconnect();
+ }
+ });
+ }
+
+ const id = "@test.embedded.web.extension";
+
+ // Extensions.generateXPI is used here (and in the other hybrid addons tests in this same
+ // test dir) to be able to generate an xpi with the directory layout that we expect from
+ // an hybrid legacy+webextension addon (where all the embedded webextension resources are
+ // loaded from a 'webextension/' directory).
+ let fakeHybridAddonFile = Extension.generateZipFile({
+ "webextension/manifest.json": {
+ applications: {gecko: {id}},
+ name: "embedded webextension name",
+ manifest_version: 2,
+ version: "1.0",
+ background: {
+ scripts: ["bg.js"],
+ },
+ },
+ "webextension/bg.js": `new ${backgroundScript}`,
+ });
+
+ // Remove the generated xpi file and flush the its jar cache
+ // on cleanup.
+ do_register_cleanup(() => {
+ Services.obs.notifyObservers(fakeHybridAddonFile, "flush-cache-entry", null);
+ fakeHybridAddonFile.remove(false);
+ });
+
+ let fileURI = Services.io.newFileURI(fakeHybridAddonFile);
+ let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null);
+
+ let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({
+ id, resourceURI,
+ });
+
+ ok(embeddedExtension, "Got the embeddedExtension object");
+
+ equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 1,
+ "Got the expected number of tracked embedded extension instances");
+
+ do_print("waiting embeddedExtension.startup");
+ let embeddedExtensionAPI = yield embeddedExtension.startup();
+ ok(embeddedExtensionAPI, "Got the embeddedExtensionAPI object");
+
+ let waitConnectPort = new Promise(resolve => {
+ let {browser} = embeddedExtensionAPI;
+ browser.runtime.onConnect.addListener(port => {
+ resolve(port);
+ });
+ });
+
+ let port = yield waitConnectPort;
+
+ ok(port, "Got the Port API object");
+
+ let waitPortMessage = new Promise(resolve => {
+ port.onMessage.addListener((msg) => {
+ resolve(msg);
+ });
+ });
+
+ port.postMessage("legacy_extension -> webextension");
+
+ let msg = yield waitPortMessage;
+
+ equal(msg, "webextension -> legacy_extension",
+ "LegacyExtensionContext received the expected message from the webextension");
+
+ let waitForDisconnect = new Promise(resolve => {
+ port.onDisconnect.addListener(resolve);
+ });
+
+ do_print("Wait for the disconnect port event");
+ yield waitForDisconnect;
+ do_print("Got the disconnect port event");
+
+ yield embeddedExtension.shutdown();
+
+ equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 0,
+ "EmbeddedExtension instances has been untracked from the EmbeddedExtensionManager");
+});
+
+function* createManifestErrorTestCase(id, xpi, expectedError) {
+ // Remove the generated xpi file and flush the its jar cache
+ // on cleanup.
+ do_register_cleanup(() => {
+ Services.obs.notifyObservers(xpi, "flush-cache-entry", null);
+ xpi.remove(false);
+ });
+
+ let fileURI = Services.io.newFileURI(xpi);
+ let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null);
+
+ let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({
+ id, resourceURI,
+ });
+
+ yield Assert.rejects(embeddedExtension.startup(), expectedError,
+ "embedded extension startup rejected");
+
+ // Shutdown a "never-started" addon with an embedded webextension should not
+ // raise any exception, and if it does this test will fail.
+ yield embeddedExtension.shutdown();
+}
+
+add_task(function* test_startup_error_empty_manifest() {
+ const id = "empty-manifest@test.embedded.web.extension";
+ const files = {
+ "webextension/manifest.json": ``,
+ };
+ const expectedError = "(NS_BASE_STREAM_CLOSED)";
+
+ let fakeHybridAddonFile = Extension.generateZipFile(files);
+
+ yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
+});
+
+add_task(function* test_startup_error_invalid_json_manifest() {
+ const id = "invalid-json-manifest@test.embedded.web.extension";
+ const files = {
+ "webextension/manifest.json": `{ "name": }`,
+ };
+ const expectedError = "JSON.parse:";
+
+ let fakeHybridAddonFile = Extension.generateZipFile(files);
+
+ yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
+});
+
+add_task(function* test_startup_error_blocking_validation_errors() {
+ const id = "blocking-manifest-validation-error@test.embedded.web.extension";
+ const files = {
+ "webextension/manifest.json": {
+ name: "embedded webextension name",
+ manifest_version: 2,
+ version: "1.0",
+ background: {
+ scripts: {},
+ },
+ },
+ };
+
+ function expectedError(actual) {
+ if (actual.errors && actual.errors.length == 1 &&
+ actual.errors[0].startsWith("Reading manifest:")) {
+ return true;
+ }
+
+ return false;
+ }
+
+ let fakeHybridAddonFile = Extension.generateZipFile(files);
+
+ yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js
new file mode 100644
index 000000000..0f0b41085
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js
@@ -0,0 +1,50 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+function backgroundScript() {
+ let hasRun = localStorage.getItem("has-run");
+ let result;
+ if (!hasRun) {
+ localStorage.setItem("has-run", "yup");
+ localStorage.setItem("test-item", "item1");
+ result = "item1";
+ } else {
+ let data = localStorage.getItem("test-item");
+ if (data == "item1") {
+ localStorage.setItem("test-item", "item2");
+ result = "item2";
+ } else if (data == "item2") {
+ localStorage.removeItem("test-item");
+ result = "deleted";
+ } else if (!data) {
+ localStorage.clear();
+ result = "cleared";
+ }
+ }
+ browser.test.sendMessage("result", result);
+ browser.test.notifyPass("localStorage");
+}
+
+const ID = "test-webextension@mozilla.com";
+let extensionData = {
+ manifest: {applications: {gecko: {id: ID}}},
+ background: backgroundScript,
+};
+
+add_task(function* test_localStorage() {
+ const RESULTS = ["item1", "item2", "deleted", "cleared", "item1"];
+
+ for (let expected of RESULTS) {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+
+ let actual = yield extension.awaitMessage("result");
+
+ yield extension.awaitFinish("localStorage");
+ yield extension.unload();
+
+ equal(actual, expected, "got expected localStorage data");
+ }
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_management.js b/toolkit/components/webextensions/test/xpcshell/test_ext_management.js
new file mode 100644
index 000000000..b19554a57
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_management.js
@@ -0,0 +1,20 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_management_schema() {
+ function background() {
+ browser.test.assertTrue(browser.management, "browser.management API exists");
+ browser.test.notifyPass("management-schema");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["management"],
+ },
+ background: `(${background})()`,
+ });
+ yield extension.startup();
+ yield extension.awaitFinish("management-schema");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js b/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js
new file mode 100644
index 000000000..7d80a9c23
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js
@@ -0,0 +1,135 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+Cu.import("resource://gre/modules/AddonManager.jsm");
+Cu.import("resource://testing-common/AddonTestUtils.jsm");
+Cu.import("resource://testing-common/MockRegistrar.jsm");
+
+const {promiseAddonByID} = AddonTestUtils;
+const id = "uninstall_self_test@tests.mozilla.com";
+
+const manifest = {
+ applications: {
+ gecko: {
+ id,
+ },
+ },
+ name: "test extension name",
+ version: "1.0",
+};
+
+const waitForUninstalled = () => new Promise(resolve => {
+ const listener = {
+ onUninstalled: (addon) => {
+ equal(addon.id, id, "The expected add-on has been uninstalled");
+ AddonManager.getAddonByID(addon.id, checkedAddon => {
+ equal(checkedAddon, null, "Add-on no longer exists");
+ AddonManager.removeAddonListener(listener);
+ resolve();
+ });
+ },
+ };
+ AddonManager.addAddonListener(listener);
+});
+
+let promptService = {
+ _response: null,
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]),
+ confirmEx: function(...args) {
+ this._confirmExArgs = args;
+ return this._response;
+ },
+};
+
+add_task(function* setup() {
+ let fakePromptService = MockRegistrar.register("@mozilla.org/embedcomp/prompt-service;1", promptService);
+ do_register_cleanup(() => {
+ MockRegistrar.unregister(fakePromptService);
+ });
+ yield ExtensionTestUtils.startAddonManager();
+});
+
+add_task(function* test_management_uninstall_no_prompt() {
+ function background() {
+ browser.test.onMessage.addListener(msg => {
+ browser.management.uninstallSelf();
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest,
+ background,
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ let addon = yield promiseAddonByID(id);
+ notEqual(addon, null, "Add-on is installed");
+ extension.sendMessage("uninstall");
+ yield waitForUninstalled();
+ yield extension.markUnloaded();
+ Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null);
+});
+
+add_task(function* test_management_uninstall_prompt_uninstall() {
+ promptService._response = 0;
+
+ function background() {
+ browser.test.onMessage.addListener(msg => {
+ browser.management.uninstallSelf({showConfirmDialog: true});
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest,
+ background,
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ let addon = yield promiseAddonByID(id);
+ notEqual(addon, null, "Add-on is installed");
+ extension.sendMessage("uninstall");
+ yield waitForUninstalled();
+ yield extension.markUnloaded();
+
+ // Test localization strings
+ equal(promptService._confirmExArgs[1], `Uninstall ${manifest.name}`);
+ equal(promptService._confirmExArgs[2],
+ `The extension “${manifest.name}†is requesting to be uninstalled. What would you like to do?`);
+ equal(promptService._confirmExArgs[4], "Uninstall");
+ equal(promptService._confirmExArgs[5], "Keep Installed");
+ Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null);
+});
+
+add_task(function* test_management_uninstall_prompt_keep() {
+ promptService._response = 1;
+
+ function background() {
+ browser.test.onMessage.addListener(async msg => {
+ await browser.test.assertRejects(
+ browser.management.uninstallSelf({showConfirmDialog: true}),
+ "User cancelled uninstall of extension",
+ "Expected rejection when user declines uninstall");
+
+ browser.test.sendMessage("uninstall-rejected");
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest,
+ background,
+ useAddonManager: "temporary",
+ });
+
+ yield extension.startup();
+ let addon = yield promiseAddonByID(id);
+ notEqual(addon, null, "Add-on is installed");
+ extension.sendMessage("uninstall");
+ yield extension.awaitMessage("uninstall-rejected");
+ addon = yield promiseAddonByID(id);
+ notEqual(addon, null, "Add-on remains installed");
+ yield extension.unload();
+ Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js
new file mode 100644
index 000000000..2b0084980
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js
@@ -0,0 +1,30 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+
+add_task(function* test_manifest_csp() {
+ let normalized = yield ExtensionTestUtils.normalizeManifest({
+ "content_security_policy": "script-src 'self'; object-src 'none'",
+ });
+
+ equal(normalized.error, undefined, "Should not have an error");
+ equal(normalized.errors.length, 0, "Should not have warnings");
+ equal(normalized.value.content_security_policy,
+ "script-src 'self'; object-src 'none'",
+ "Should have the expected poilcy string");
+
+
+ normalized = yield ExtensionTestUtils.normalizeManifest({
+ "content_security_policy": "object-src 'none'",
+ });
+
+ equal(normalized.error, undefined, "Should not have an error");
+
+ Assert.deepEqual(normalized.errors,
+ ["Error processing content_security_policy: SyntaxError: Policy is missing a required \u2018script-src\u2019 directive"],
+ "Should have the expected warning");
+
+ equal(normalized.value.content_security_policy, null,
+ "Invalid policy string should be omitted");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js
new file mode 100644
index 000000000..94649692e
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js
@@ -0,0 +1,27 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+
+add_task(function* test_manifest_incognito() {
+ let normalized = yield ExtensionTestUtils.normalizeManifest({
+ "incognito": "spanning",
+ });
+
+ equal(normalized.error, undefined, "Should not have an error");
+ equal(normalized.errors.length, 0, "Should not have warnings");
+ equal(normalized.value.incognito,
+ "spanning",
+ "Should have the expected incognito string");
+
+ normalized = yield ExtensionTestUtils.normalizeManifest({
+ "incognito": "split",
+ });
+
+ equal(normalized.error, undefined, "Should not have an error");
+ Assert.deepEqual(normalized.errors,
+ ['Error processing incognito: Invalid enumeration value "split"'],
+ "Should have the expected warning");
+ equal(normalized.value.incognito, null,
+ "Invalid incognito string should be omitted");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js
new file mode 100644
index 000000000..fad5661bb
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js
@@ -0,0 +1,13 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+
+add_task(function* test_manifest_minimum_chrome_version() {
+ let normalized = yield ExtensionTestUtils.normalizeManifest({
+ "minimum_chrome_version": "42",
+ });
+
+ equal(normalized.error, undefined, "Should not have an error");
+ equal(normalized.errors.length, 0, "Should not have warnings");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js
new file mode 100644
index 000000000..5a6b628f5
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js
@@ -0,0 +1,514 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* globals chrome */
+
+const PREF_MAX_READ = "webextensions.native-messaging.max-input-message-bytes";
+const PREF_MAX_WRITE = "webextensions.native-messaging.max-output-message-bytes";
+
+const ECHO_BODY = String.raw`
+ import struct
+ import sys
+
+ while True:
+ rawlen = sys.stdin.read(4)
+ if len(rawlen) == 0:
+ sys.exit(0)
+ msglen = struct.unpack('@I', rawlen)[0]
+ msg = sys.stdin.read(msglen)
+
+ sys.stdout.write(struct.pack('@I', msglen))
+ sys.stdout.write(msg)
+`;
+
+const INFO_BODY = String.raw`
+ import json
+ import os
+ import struct
+ import sys
+
+ msg = json.dumps({"args": sys.argv, "cwd": os.getcwd()})
+ sys.stdout.write(struct.pack('@I', len(msg)))
+ sys.stdout.write(msg)
+ sys.exit(0)
+`;
+
+const STDERR_LINES = ["hello stderr", "this should be a separate line"];
+let STDERR_MSG = STDERR_LINES.join("\\n");
+
+const STDERR_BODY = String.raw`
+ import sys
+ sys.stderr.write("${STDERR_MSG}")
+`;
+
+const SCRIPTS = [
+ {
+ name: "echo",
+ description: "a native app that echoes back messages it receives",
+ script: ECHO_BODY.replace(/^ {2}/gm, ""),
+ },
+ {
+ name: "info",
+ description: "a native app that gives some info about how it was started",
+ script: INFO_BODY.replace(/^ {2}/gm, ""),
+ },
+ {
+ name: "stderr",
+ description: "a native app that writes to stderr and then exits",
+ script: STDERR_BODY.replace(/^ {2}/gm, ""),
+ },
+];
+
+add_task(function* setup() {
+ yield setupHosts(SCRIPTS);
+});
+
+// Test the basic operation of native messaging with a simple
+// script that echoes back whatever message is sent to it.
+add_task(function* test_happy_path() {
+ function background() {
+ let port = browser.runtime.connectNative("echo");
+ port.onMessage.addListener(msg => {
+ browser.test.sendMessage("message", msg);
+ });
+ browser.test.onMessage.addListener((what, payload) => {
+ if (what == "send") {
+ if (payload._json) {
+ let json = payload._json;
+ payload.toJSON = () => json;
+ delete payload._json;
+ }
+ port.postMessage(payload);
+ }
+ });
+ browser.test.sendMessage("ready");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+ const tests = [
+ {
+ data: "this is a string",
+ what: "simple string",
+ },
+ {
+ data: "Это юникода",
+ what: "unicode string",
+ },
+ {
+ data: {test: "hello"},
+ what: "simple object",
+ },
+ {
+ data: {
+ what: "An object with a few properties",
+ number: 123,
+ bool: true,
+ nested: {what: "another object"},
+ },
+ what: "object with several properties",
+ },
+
+ {
+ data: {
+ ignoreme: true,
+ _json: {data: "i have a tojson method"},
+ },
+ expected: {data: "i have a tojson method"},
+ what: "object with toJSON() method",
+ },
+ ];
+ for (let test of tests) {
+ extension.sendMessage("send", test.data);
+ let response = yield extension.awaitMessage("message");
+ let expected = test.expected || test.data;
+ deepEqual(response, expected, `Echoed a message of type ${test.what}`);
+ }
+
+ let procCount = yield getSubprocessCount();
+ equal(procCount, 1, "subprocess is still running");
+ let exitPromise = waitForSubprocessExit();
+ yield extension.unload();
+ yield exitPromise;
+});
+
+if (AppConstants.platform == "win") {
+ // "relative.echo" has a relative path in the host manifest.
+ add_task(function* test_relative_path() {
+ function background() {
+ let port = browser.runtime.connectNative("relative.echo");
+ let MSG = "test relative echo path";
+ port.onMessage.addListener(msg => {
+ browser.test.assertEq(MSG, msg, "Got expected message back");
+ browser.test.sendMessage("done");
+ });
+ port.postMessage(MSG);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("done");
+
+ let procCount = yield getSubprocessCount();
+ equal(procCount, 1, "subprocess is still running");
+ let exitPromise = waitForSubprocessExit();
+ yield extension.unload();
+ yield exitPromise;
+ });
+}
+
+// Test sendNativeMessage()
+add_task(function* test_sendNativeMessage() {
+ async function background() {
+ let MSG = {test: "hello world"};
+
+ // Check error handling
+ await browser.test.assertRejects(
+ browser.runtime.sendNativeMessage("nonexistent", MSG),
+ /Attempt to postMessage on disconnected port/,
+ "sendNativeMessage() to a nonexistent app failed");
+
+ // Check regular message exchange
+ let reply = await browser.runtime.sendNativeMessage("echo", MSG);
+
+ let expected = JSON.stringify(MSG);
+ let received = JSON.stringify(reply);
+ browser.test.assertEq(expected, received, "Received echoed native message");
+
+ browser.test.sendMessage("finished");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("finished");
+
+ // With sendNativeMessage(), the subprocess should be disconnected
+ // after exchanging a single message.
+ yield waitForSubprocessExit();
+
+ yield extension.unload();
+});
+
+// Test calling Port.disconnect()
+add_task(function* test_disconnect() {
+ function background() {
+ let port = browser.runtime.connectNative("echo");
+ port.onMessage.addListener((msg, msgPort) => {
+ browser.test.assertEq(port, msgPort, "onMessage handler should receive the port as the second argument");
+ browser.test.sendMessage("message", msg);
+ });
+ port.onDisconnect.addListener(msgPort => {
+ browser.test.fail("onDisconnect should not be called for disconnect()");
+ });
+ browser.test.onMessage.addListener((what, payload) => {
+ if (what == "send") {
+ if (payload._json) {
+ let json = payload._json;
+ payload.toJSON = () => json;
+ delete payload._json;
+ }
+ port.postMessage(payload);
+ } else if (what == "disconnect") {
+ try {
+ port.disconnect();
+ browser.test.sendMessage("disconnect-result", {success: true});
+ } catch (err) {
+ browser.test.sendMessage("disconnect-result", {
+ success: false,
+ errmsg: err.message,
+ });
+ }
+ }
+ });
+ browser.test.sendMessage("ready");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage("send", "test");
+ let response = yield extension.awaitMessage("message");
+ equal(response, "test", "Echoed a string");
+
+ let procCount = yield getSubprocessCount();
+ equal(procCount, 1, "subprocess is running");
+
+ extension.sendMessage("disconnect");
+ response = yield extension.awaitMessage("disconnect-result");
+ equal(response.success, true, "disconnect succeeded");
+
+ do_print("waiting for subprocess to exit");
+ yield waitForSubprocessExit();
+ procCount = yield getSubprocessCount();
+ equal(procCount, 0, "subprocess is no longer running");
+
+ extension.sendMessage("disconnect");
+ response = yield extension.awaitMessage("disconnect-result");
+ equal(response.success, true, "second call to disconnect silently ignored");
+
+ yield extension.unload();
+});
+
+// Test the limit on message size for writing
+add_task(function* test_write_limit() {
+ Services.prefs.setIntPref(PREF_MAX_WRITE, 10);
+ function clearPref() {
+ Services.prefs.clearUserPref(PREF_MAX_WRITE);
+ }
+ do_register_cleanup(clearPref);
+
+ function background() {
+ const PAYLOAD = "0123456789A";
+ let port = browser.runtime.connectNative("echo");
+ try {
+ port.postMessage(PAYLOAD);
+ browser.test.sendMessage("result", null);
+ } catch (ex) {
+ browser.test.sendMessage("result", ex.message);
+ }
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+
+ let errmsg = yield extension.awaitMessage("result");
+ notEqual(errmsg, null, "native postMessage() failed for overly large message");
+
+ yield extension.unload();
+ yield waitForSubprocessExit();
+
+ clearPref();
+});
+
+// Test the limit on message size for reading
+add_task(function* test_read_limit() {
+ Services.prefs.setIntPref(PREF_MAX_READ, 10);
+ function clearPref() {
+ Services.prefs.clearUserPref(PREF_MAX_READ);
+ }
+ do_register_cleanup(clearPref);
+
+ function background() {
+ const PAYLOAD = "0123456789A";
+ let port = browser.runtime.connectNative("echo");
+ port.onDisconnect.addListener(msgPort => {
+ browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument");
+ browser.test.assertEq("Native application tried to send a message of 13 bytes, which exceeds the limit of 10 bytes.", port.error && port.error.message);
+ browser.test.sendMessage("result", "disconnected");
+ });
+ port.onMessage.addListener(msg => {
+ browser.test.sendMessage("result", "message");
+ });
+ port.postMessage(PAYLOAD);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+
+ let result = yield extension.awaitMessage("result");
+ equal(result, "disconnected", "native port disconnected on receiving large message");
+
+ yield extension.unload();
+ yield waitForSubprocessExit();
+
+ clearPref();
+});
+
+// Test that an extension without the nativeMessaging permission cannot
+// use native messaging.
+add_task(function* test_ext_permission() {
+ function background() {
+ browser.test.assertFalse("connectNative" in chrome.runtime, "chrome.runtime.connectNative does not exist without nativeMessaging permission");
+ browser.test.assertFalse("connectNative" in browser.runtime, "browser.runtime.connectNative does not exist without nativeMessaging permission");
+ browser.test.assertFalse("sendNativeMessage" in chrome.runtime, "chrome.runtime.sendNativeMessage does not exist without nativeMessaging permission");
+ browser.test.assertFalse("sendNativeMessage" in browser.runtime, "browser.runtime.sendNativeMessage does not exist without nativeMessaging permission");
+ browser.test.sendMessage("finished");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {},
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("finished");
+ yield extension.unload();
+});
+
+// Test that an extension that is not listed in allowed_extensions for
+// a native application cannot use that application.
+add_task(function* test_app_permission() {
+ function background() {
+ let port = browser.runtime.connectNative("echo");
+ port.onDisconnect.addListener(msgPort => {
+ browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument");
+ browser.test.assertEq("This extension does not have permission to use native application echo (or the application is not installed)", port.error && port.error.message);
+ browser.test.sendMessage("result", "disconnected");
+ });
+ port.onMessage.addListener(msg => {
+ browser.test.sendMessage("result", "message");
+ });
+ port.postMessage({test: "test"});
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ permissions: ["nativeMessaging"],
+ },
+ }, "somethingelse@tests.mozilla.org");
+
+ yield extension.startup();
+
+ let result = yield extension.awaitMessage("result");
+ equal(result, "disconnected", "connectNative() failed without native app permission");
+
+ yield extension.unload();
+
+ let procCount = yield getSubprocessCount();
+ equal(procCount, 0, "No child process was started");
+});
+
+// Test that the command-line arguments and working directory for the
+// native application are as expected.
+add_task(function* test_child_process() {
+ function background() {
+ let port = browser.runtime.connectNative("info");
+ port.onMessage.addListener(msg => {
+ browser.test.sendMessage("result", msg);
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+
+ let msg = yield extension.awaitMessage("result");
+ equal(msg.args.length, 2, "Received one command line argument");
+ equal(msg.args[1], getPath("info.json"), "Command line argument is the path to the native host manifest");
+ equal(msg.cwd.replace(/^\/private\//, "/"), tmpDir.path,
+ "Working directory is the directory containing the native appliation");
+
+ let exitPromise = waitForSubprocessExit();
+ yield extension.unload();
+ yield exitPromise;
+});
+
+add_task(function* test_stderr() {
+ function background() {
+ let port = browser.runtime.connectNative("stderr");
+ port.onDisconnect.addListener(msgPort => {
+ browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument");
+ browser.test.assertEq(null, port.error, "Normal application exit is not an error");
+ browser.test.sendMessage("finished");
+ });
+ }
+
+ let {messages} = yield promiseConsoleOutput(function* () {
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("finished");
+ yield extension.unload();
+
+ yield waitForSubprocessExit();
+ });
+
+ let lines = STDERR_LINES.map(line => messages.findIndex(msg => msg.message.includes(line)));
+ notEqual(lines[0], -1, "Saw first line of stderr output on the console");
+ notEqual(lines[1], -1, "Saw second line of stderr output on the console");
+ notEqual(lines[0], lines[1], "Stderr output lines are separated in the console");
+});
+
+// Test that calling connectNative() multiple times works
+// (bug 1313980 was a previous regression in this area)
+add_task(function* test_multiple_connects() {
+ async function background() {
+ function once() {
+ return new Promise(resolve => {
+ let MSG = "hello";
+ let port = browser.runtime.connectNative("echo");
+
+ port.onMessage.addListener(msg => {
+ browser.test.assertEq(MSG, msg, "Got expected message back");
+ port.disconnect();
+ resolve();
+ });
+ port.postMessage(MSG);
+ });
+ }
+
+ await once();
+ await once();
+ browser.test.notifyPass("multiple-connect");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("multiple-connect");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js
new file mode 100644
index 000000000..693f67dde
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js
@@ -0,0 +1,128 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+XPCOMUtils.defineLazyModuleGetter(this, "MockRegistry",
+ "resource://testing-common/MockRegistry.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+
+Cu.import("resource://gre/modules/Subprocess.jsm");
+
+const MAX_ROUND_TRIP_TIME_MS = AppConstants.DEBUG || AppConstants.ASAN ? 36 : 18;
+const MAX_RETRIES = 5;
+
+
+const ECHO_BODY = String.raw`
+ import struct
+ import sys
+
+ while True:
+ rawlen = sys.stdin.read(4)
+ if len(rawlen) == 0:
+ sys.exit(0)
+
+ msglen = struct.unpack('@I', rawlen)[0]
+ msg = sys.stdin.read(msglen)
+
+ sys.stdout.write(struct.pack('@I', msglen))
+ sys.stdout.write(msg)
+`;
+
+const SCRIPTS = [
+ {
+ name: "echo",
+ description: "A native app that echoes back messages it receives",
+ script: ECHO_BODY.replace(/^ {2}/gm, ""),
+ },
+];
+
+add_task(function* setup() {
+ yield setupHosts(SCRIPTS);
+});
+
+add_task(function* test_round_trip_perf() {
+ let extension = ExtensionTestUtils.loadExtension({
+ background() {
+ browser.test.onMessage.addListener(msg => {
+ if (msg != "run-tests") {
+ return;
+ }
+
+ let port = browser.runtime.connectNative("echo");
+
+ function next() {
+ port.postMessage({
+ "Lorem": {
+ "ipsum": {
+ "dolor": [
+ "sit amet",
+ "consectetur adipiscing elit",
+ "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
+ ],
+ "Ut enim": [
+ "ad minim veniam",
+ "quis nostrud exercitation ullamco",
+ "laboris nisi ut aliquip ex ea commodo consequat.",
+ ],
+ "Duis": [
+ "aute irure dolor in reprehenderit in",
+ "voluptate velit esse cillum dolore eu",
+ "fugiat nulla pariatur.",
+ ],
+ "Excepteur": [
+ "sint occaecat cupidatat non proident",
+ "sunt in culpa qui officia deserunt",
+ "mollit anim id est laborum.",
+ ],
+ },
+ },
+ });
+ }
+
+ const COUNT = 1000;
+ let now;
+ function finish() {
+ let roundTripTime = (Date.now() - now) / COUNT;
+
+ port.disconnect();
+ browser.test.sendMessage("result", roundTripTime);
+ }
+
+ let count = 0;
+ port.onMessage.addListener(() => {
+ if (count == 0) {
+ // Skip the first round, since it includes the time it takes
+ // the app to start up.
+ now = Date.now();
+ }
+
+ if (count++ <= COUNT) {
+ next();
+ } else {
+ finish();
+ }
+ });
+
+ next();
+ });
+ },
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+
+ let roundTripTime = Infinity;
+ for (let i = 0; i < MAX_RETRIES && roundTripTime > MAX_ROUND_TRIP_TIME_MS; i++) {
+ extension.sendMessage("run-tests");
+ roundTripTime = yield extension.awaitMessage("result");
+ }
+
+ yield extension.unload();
+
+ ok(roundTripTime <= MAX_ROUND_TRIP_TIME_MS,
+ `Expected round trip time (${roundTripTime}ms) to be less than ${MAX_ROUND_TRIP_TIME_MS}ms`);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js
new file mode 100644
index 000000000..a75a1d49d
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js
@@ -0,0 +1,82 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+const WONTDIE_BODY = String.raw`
+ import signal
+ import struct
+ import sys
+ import time
+
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
+
+ def spin():
+ while True:
+ try:
+ signal.pause()
+ except AttributeError:
+ time.sleep(5)
+
+ while True:
+ rawlen = sys.stdin.read(4)
+ if len(rawlen) == 0:
+ spin()
+
+ msglen = struct.unpack('@I', rawlen)[0]
+ msg = sys.stdin.read(msglen)
+
+ sys.stdout.write(struct.pack('@I', msglen))
+ sys.stdout.write(msg)
+`;
+
+const SCRIPTS = [
+ {
+ name: "wontdie",
+ description: "a native app that does not exit when stdin closes or on SIGTERM",
+ script: WONTDIE_BODY.replace(/^ {2}/gm, ""),
+ },
+];
+
+add_task(function* setup() {
+ yield setupHosts(SCRIPTS);
+});
+
+
+// Test that an unresponsive native application still gets killed eventually
+add_task(function* test_unresponsive_native_app() {
+ // XXX expose GRACEFUL_SHUTDOWN_TIME as a pref and reduce it
+ // just for this test?
+
+ function background() {
+ let port = browser.runtime.connectNative("wontdie");
+
+ const MSG = "echo me";
+ // bounce a message to make sure the process actually starts
+ port.onMessage.addListener(msg => {
+ browser.test.assertEq(msg, MSG, "Received echoed message");
+ browser.test.sendMessage("ready");
+ });
+ port.postMessage(MSG);
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ manifest: {
+ applications: {gecko: {id: ID}},
+ permissions: ["nativeMessaging"],
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ let procCount = yield getSubprocessCount();
+ equal(procCount, 1, "subprocess is running");
+
+ let exitPromise = waitForSubprocessExit();
+ yield extension.unload();
+ yield exitPromise;
+
+ procCount = yield getSubprocessCount();
+ equal(procCount, 0, "subprocess was succesfully killed");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js b/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js
new file mode 100644
index 000000000..6f8b553fc
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js
@@ -0,0 +1,30 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+function backgroundScript() {
+ function listener() {
+ browser.test.notifyFail("listener should not be invoked");
+ }
+
+ browser.runtime.onMessage.addListener(listener);
+ browser.runtime.onMessage.removeListener(listener);
+ browser.runtime.sendMessage("hello");
+
+ // Make sure that, if we somehow fail to remove the listener, then we'll run
+ // the listener before the test is marked as passing.
+ setTimeout(function() {
+ browser.test.notifyPass("onmessage_removelistener");
+ }, 0);
+}
+
+let extensionData = {
+ background: backgroundScript,
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitFinish("onmessage_removelistener");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js
new file mode 100644
index 000000000..2a1342cde
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js
@@ -0,0 +1,23 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_connect_without_listener() {
+ function background() {
+ let port = browser.runtime.connect();
+ port.onDisconnect.addListener(() => {
+ browser.test.assertEq("Could not establish connection. Receiving end does not exist.", port.error && port.error.message);
+ browser.test.notifyPass("port.onDisconnect was called");
+ });
+ }
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("port.onDisconnect was called");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js
new file mode 100644
index 000000000..a280206fa
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js
@@ -0,0 +1,26 @@
+/* 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";
+
+add_task(function* setup() {
+ ExtensionTestUtils.mockAppInfo();
+});
+
+add_task(function* test_getBrowserInfo() {
+ async function background() {
+ let info = await browser.runtime.getBrowserInfo();
+
+ browser.test.assertEq(info.name, "XPCShell", "name is valid");
+ browser.test.assertEq(info.vendor, "Mozilla", "vendor is Mozilla");
+ browser.test.assertEq(info.version, "48", "version is correct");
+ browser.test.assertEq(info.buildID, "20160315", "buildID is correct");
+
+ browser.test.notifyPass("runtime.getBrowserInfo");
+ }
+
+ const extension = ExtensionTestUtils.loadExtension({background});
+ yield extension.startup();
+ yield extension.awaitFinish("runtime.getBrowserInfo");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js
new file mode 100644
index 000000000..29bad0c10
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js
@@ -0,0 +1,25 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+function backgroundScript() {
+ browser.runtime.getPlatformInfo(info => {
+ let validOSs = ["mac", "win", "android", "cros", "linux", "openbsd"];
+ let validArchs = ["arm", "x86-32", "x86-64"];
+
+ browser.test.assertTrue(validOSs.indexOf(info.os) != -1, "OS is valid");
+ browser.test.assertTrue(validArchs.indexOf(info.arch) != -1, "Architecture is valid");
+ browser.test.notifyPass("runtime.getPlatformInfo");
+ });
+}
+
+let extensionData = {
+ background: backgroundScript,
+};
+
+add_task(function* test_contentscript() {
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitFinish("runtime.getPlatformInfo");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js
new file mode 100644
index 000000000..fa6461412
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js
@@ -0,0 +1,337 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+XPCOMUtils.defineLazyGetter(this, "Management", () => {
+ const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {});
+ return Management;
+});
+
+const {
+ createAppInfo,
+ createTempWebExtensionFile,
+ promiseAddonByID,
+ promiseAddonEvent,
+ promiseCompleteAllInstalls,
+ promiseFindAddonUpdates,
+ promiseRestartManager,
+ promiseShutdownManager,
+ promiseStartupManager,
+} = AddonTestUtils;
+
+AddonTestUtils.init(this);
+
+// Allow for unsigned addons.
+AddonTestUtils.overrideCertDB();
+
+createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "42");
+
+function awaitEvent(eventName) {
+ return new Promise(resolve => {
+ let listener = (_eventName, ...args) => {
+ if (_eventName === eventName) {
+ Management.off(eventName, listener);
+ resolve(...args);
+ }
+ };
+
+ Management.on(eventName, listener);
+ });
+}
+
+function background() {
+ let onInstalledDetails = null;
+ let onStartupFired = false;
+
+ browser.runtime.onInstalled.addListener(details => {
+ onInstalledDetails = details;
+ });
+
+ browser.runtime.onStartup.addListener(() => {
+ onStartupFired = true;
+ });
+
+ browser.test.onMessage.addListener(message => {
+ if (message === "get-on-installed-details") {
+ onInstalledDetails = onInstalledDetails || {fired: false};
+ browser.test.sendMessage("on-installed-details", onInstalledDetails);
+ } else if (message === "did-on-startup-fire") {
+ browser.test.sendMessage("on-startup-fired", onStartupFired);
+ } else if (message === "reload-extension") {
+ browser.runtime.reload();
+ }
+ });
+
+ browser.runtime.onUpdateAvailable.addListener(details => {
+ browser.test.sendMessage("reloading");
+ browser.runtime.reload();
+ });
+}
+
+function* expectEvents(extension, {onStartupFired, onInstalledFired, onInstalledReason}) {
+ extension.sendMessage("get-on-installed-details");
+ let details = yield extension.awaitMessage("on-installed-details");
+ if (onInstalledFired) {
+ equal(details.reason, onInstalledReason, "runtime.onInstalled fired with the correct reason");
+ } else {
+ equal(details.fired, onInstalledFired, "runtime.onInstalled should not have fired");
+ }
+
+ extension.sendMessage("did-on-startup-fire");
+ let fired = yield extension.awaitMessage("on-startup-fired");
+ equal(fired, onStartupFired, `Expected runtime.onStartup to ${onStartupFired ? "" : "not "} fire`);
+}
+
+add_task(function* test_should_fire_on_addon_update() {
+ const EXTENSION_ID = "test_runtime_on_installed_addon_update@tests.mozilla.org";
+
+ const PREF_EM_CHECK_UPDATE_SECURITY = "extensions.checkUpdateSecurity";
+
+ // The test extension uses an insecure update url.
+ Services.prefs.setBoolPref(PREF_EM_CHECK_UPDATE_SECURITY, false);
+
+ const testServer = createHttpServer();
+ const port = testServer.identity.primaryPort;
+
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "permanent",
+ manifest: {
+ "version": "1.0",
+ "applications": {
+ "gecko": {
+ "id": EXTENSION_ID,
+ "update_url": `http://localhost:${port}/test_update.json`,
+ },
+ },
+ },
+ background,
+ });
+
+ testServer.registerPathHandler("/test_update.json", (request, response) => {
+ response.write(`{
+ "addons": {
+ "${EXTENSION_ID}": {
+ "updates": [
+ {
+ "version": "2.0",
+ "update_link": "http://localhost:${port}/addons/test_runtime_on_installed-2.0.xpi"
+ }
+ ]
+ }
+ }
+ }`);
+ });
+
+ let webExtensionFile = createTempWebExtensionFile({
+ manifest: {
+ version: "2.0",
+ applications: {
+ gecko: {
+ id: EXTENSION_ID,
+ },
+ },
+ },
+ background,
+ });
+
+ testServer.registerFile("/addons/test_runtime_on_installed-2.0.xpi", webExtensionFile);
+
+ yield promiseStartupManager();
+
+ yield extension.startup();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: true,
+ onInstalledReason: "install",
+ });
+
+ let addon = yield promiseAddonByID(EXTENSION_ID);
+ equal(addon.version, "1.0", "The installed addon has the correct version");
+
+ let update = yield promiseFindAddonUpdates(addon);
+ let install = update.updateAvailable;
+
+ let promiseInstalled = promiseAddonEvent("onInstalled");
+ yield promiseCompleteAllInstalls([install]);
+
+ yield extension.awaitMessage("reloading");
+
+ let startupPromise = awaitEvent("ready");
+
+ let [updated_addon] = yield promiseInstalled;
+ equal(updated_addon.version, "2.0", "The updated addon has the correct version");
+
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: true,
+ onInstalledReason: "update",
+ });
+
+ yield extension.unload();
+
+ yield updated_addon.uninstall();
+ yield promiseShutdownManager();
+});
+
+add_task(function* test_should_fire_on_browser_update() {
+ const EXTENSION_ID = "test_runtime_on_installed_browser_update@tests.mozilla.org";
+
+ yield promiseStartupManager();
+
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "permanent",
+ manifest: {
+ "version": "1.0",
+ "applications": {
+ "gecko": {
+ "id": EXTENSION_ID,
+ },
+ },
+ },
+ background,
+ });
+
+ yield extension.startup();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: true,
+ onInstalledReason: "install",
+ });
+
+ let startupPromise = awaitEvent("ready");
+ yield promiseRestartManager("1");
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: true,
+ onInstalledFired: false,
+ });
+
+ // Update the browser.
+ startupPromise = awaitEvent("ready");
+ yield promiseRestartManager("2");
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: true,
+ onInstalledFired: true,
+ onInstalledReason: "browser_update",
+ });
+
+ // Restart the browser.
+ startupPromise = awaitEvent("ready");
+ yield promiseRestartManager("2");
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: true,
+ onInstalledFired: false,
+ });
+
+ // Update the browser again.
+ startupPromise = awaitEvent("ready");
+ yield promiseRestartManager("3");
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: true,
+ onInstalledFired: true,
+ onInstalledReason: "browser_update",
+ });
+
+ yield extension.unload();
+
+ yield promiseShutdownManager();
+});
+
+add_task(function* test_should_not_fire_on_reload() {
+ const EXTENSION_ID = "test_runtime_on_installed_reload@tests.mozilla.org";
+
+ yield promiseStartupManager();
+
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "permanent",
+ manifest: {
+ "version": "1.0",
+ "applications": {
+ "gecko": {
+ "id": EXTENSION_ID,
+ },
+ },
+ },
+ background,
+ });
+
+ yield extension.startup();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: true,
+ onInstalledReason: "install",
+ });
+
+ let startupPromise = awaitEvent("ready");
+ extension.sendMessage("reload-extension");
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: false,
+ });
+
+ yield extension.unload();
+ yield promiseShutdownManager();
+});
+
+add_task(function* test_should_not_fire_on_restart() {
+ const EXTENSION_ID = "test_runtime_on_installed_restart@tests.mozilla.org";
+
+ yield promiseStartupManager();
+
+ let extension = ExtensionTestUtils.loadExtension({
+ useAddonManager: "permanent",
+ manifest: {
+ "version": "1.0",
+ "applications": {
+ "gecko": {
+ "id": EXTENSION_ID,
+ },
+ },
+ },
+ background,
+ });
+
+ yield extension.startup();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: true,
+ onInstalledReason: "install",
+ });
+
+ let addon = yield promiseAddonByID(EXTENSION_ID);
+ addon.userDisabled = true;
+
+ let startupPromise = awaitEvent("ready");
+ addon.userDisabled = false;
+ extension.extension = yield startupPromise;
+ extension.attachListeners();
+
+ yield expectEvents(extension, {
+ onStartupFired: false,
+ onInstalledFired: false,
+ });
+
+ yield extension.markUnloaded();
+ yield promiseShutdownManager();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js
new file mode 100644
index 000000000..fec8e13dd
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js
@@ -0,0 +1,79 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* tabsSendMessageReply() {
+ function background() {
+ browser.runtime.onMessage.addListener((msg, sender, respond) => {
+ if (msg == "respond-now") {
+ respond(msg);
+ } else if (msg == "respond-soon") {
+ setTimeout(() => { respond(msg); }, 0);
+ return true;
+ } else if (msg == "respond-promise") {
+ return Promise.resolve(msg);
+ } else if (msg == "respond-never") {
+ return;
+ } else if (msg == "respond-error") {
+ return Promise.reject(new Error(msg));
+ } else if (msg == "throw-error") {
+ throw new Error(msg);
+ }
+ });
+
+ browser.runtime.onMessage.addListener((msg, sender, respond) => {
+ if (msg == "respond-now") {
+ respond("hello");
+ } else if (msg == "respond-now-2") {
+ respond(msg);
+ }
+ });
+
+ let childFrame = document.createElement("iframe");
+ childFrame.src = "extensionpage.html";
+ document.body.appendChild(childFrame);
+ }
+
+ function senderScript() {
+ Promise.all([
+ browser.runtime.sendMessage("respond-now"),
+ browser.runtime.sendMessage("respond-now-2"),
+ new Promise(resolve => browser.runtime.sendMessage("respond-soon", resolve)),
+ browser.runtime.sendMessage("respond-promise"),
+ browser.runtime.sendMessage("respond-never"),
+ new Promise(resolve => {
+ browser.runtime.sendMessage("respond-never", response => { resolve(response); });
+ }),
+
+ browser.runtime.sendMessage("respond-error").catch(error => Promise.resolve({error})),
+ browser.runtime.sendMessage("throw-error").catch(error => Promise.resolve({error})),
+ ]).then(([respondNow, respondNow2, respondSoon, respondPromise, respondNever, respondNever2, respondError, throwError]) => {
+ browser.test.assertEq("respond-now", respondNow, "Got the expected immediate response");
+ browser.test.assertEq("respond-now-2", respondNow2, "Got the expected immediate response from the second listener");
+ browser.test.assertEq("respond-soon", respondSoon, "Got the expected delayed response");
+ browser.test.assertEq("respond-promise", respondPromise, "Got the expected promise response");
+ browser.test.assertEq(undefined, respondNever, "Got the expected no-response resolution");
+ browser.test.assertEq(undefined, respondNever2, "Got the expected no-response resolution");
+
+ browser.test.assertEq("respond-error", respondError.error.message, "Got the expected error response");
+ browser.test.assertEq("throw-error", throwError.error.message, "Got the expected thrown error response");
+
+ browser.test.notifyPass("sendMessage");
+ }).catch(e => {
+ browser.test.fail(`Error: ${e} :: ${e.stack}`);
+ browser.test.notifyFail("sendMessage");
+ });
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ background,
+ files: {
+ "senderScript.js": senderScript,
+ "extensionpage.html": `<!DOCTYPE html><meta charset="utf-8"><script src="senderScript.js"></script>`,
+ },
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("sendMessage");
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js
new file mode 100644
index 000000000..f1a8d5a36
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js
@@ -0,0 +1,59 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_sendMessage_error() {
+ async function background() {
+ let circ = {};
+ circ.circ = circ;
+ let testCases = [
+ // [arguments, expected error string],
+ [[], "runtime.sendMessage's message argument is missing"],
+ [[null, null, null, null], "runtime.sendMessage's last argument is not a function"],
+ [[null, null, 1], "runtime.sendMessage's options argument is invalid"],
+ [[1, null, null], "runtime.sendMessage's extensionId argument is invalid"],
+ [[null, null, null, null, null], "runtime.sendMessage received too many arguments"],
+
+ // Even when the parameters are accepted, we still expect an error
+ // because there is no onMessage listener.
+ [[null, null, null], "Could not establish connection. Receiving end does not exist."],
+
+ // Structural cloning doesn't work with DOM but we fall back
+ // JSON serialization, so we don't expect another error.
+ [[null, location, null], "Could not establish connection. Receiving end does not exist."],
+
+ // Structured cloning supports cyclic self-references.
+ [[null, [circ, location], null], "cyclic object value"],
+ // JSON serialization does not support cyclic references.
+ [[null, circ, null], "Could not establish connection. Receiving end does not exist."],
+ // (the last two tests shows whether sendMessage is implemented as structured cloning).
+ ];
+
+ // Repeat all tests with the undefined value instead of null.
+ for (let [args, expectedError] of testCases.slice()) {
+ args = args.map(arg => arg === null ? undefined : arg);
+ testCases.push([args, expectedError]);
+ }
+
+ for (let [args, expectedError] of testCases) {
+ let description = `runtime.sendMessage(${args.map(String).join(", ")})`;
+
+ await browser.test.assertRejects(
+ browser.runtime.sendMessage(...args),
+ expectedError,
+ `expected error message for ${description}`);
+ }
+
+ browser.test.notifyPass("sendMessage parameter validation");
+ }
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("sendMessage parameter validation");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js
new file mode 100644
index 000000000..f906333d2
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js
@@ -0,0 +1,54 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_sendMessage_without_listener() {
+ async function background() {
+ await browser.test.assertRejects(
+ browser.runtime.sendMessage("msg"),
+ "Could not establish connection. Receiving end does not exist.",
+ "sendMessage callback was invoked");
+
+ browser.test.notifyPass("sendMessage callback was invoked");
+ }
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("sendMessage callback was invoked");
+
+ yield extension.unload();
+});
+
+add_task(function* test_chrome_sendMessage_without_listener() {
+ function background() {
+ /* globals chrome */
+ browser.test.assertEq(null, chrome.runtime.lastError, "no lastError before call");
+ let retval = chrome.runtime.sendMessage("msg");
+ browser.test.assertEq(null, chrome.runtime.lastError, "no lastError after call");
+ browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage without callback");
+
+ let isAsyncCall = false;
+ retval = chrome.runtime.sendMessage("msg", reply => {
+ browser.test.assertEq(undefined, reply, "no reply");
+ browser.test.assertTrue(isAsyncCall, "chrome.runtime.sendMessage's callback must be called asynchronously");
+ browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage with callback");
+ browser.test.assertEq("Could not establish connection. Receiving end does not exist.", chrome.runtime.lastError.message);
+ browser.test.notifyPass("finished chrome.runtime.sendMessage");
+ });
+ isAsyncCall = true;
+ }
+ let extensionData = {
+ background,
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitFinish("finished chrome.runtime.sendMessage");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js
new file mode 100644
index 000000000..e4f5e951f
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js
@@ -0,0 +1,51 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+
+"use strict";
+
+add_task(function* test_sendMessage_to_self_should_not_trigger_onMessage() {
+ async function background() {
+ browser.runtime.onMessage.addListener(msg => {
+ browser.test.assertEq("msg from child", msg);
+ browser.test.notifyPass("sendMessage did not call same-frame onMessage");
+ });
+
+ browser.test.onMessage.addListener(msg => {
+ browser.test.assertEq("sendMessage with a listener in another frame", msg);
+ browser.runtime.sendMessage("should only reach another frame");
+ });
+
+ await browser.test.assertRejects(
+ browser.runtime.sendMessage("should not trigger same-frame onMessage"),
+ "Could not establish connection. Receiving end does not exist.");
+
+ let anotherFrame = document.createElement("iframe");
+ anotherFrame.src = browser.extension.getURL("extensionpage.html");
+ document.body.appendChild(anotherFrame);
+ }
+
+ function lastScript() {
+ browser.runtime.onMessage.addListener(msg => {
+ browser.test.assertEq("should only reach another frame", msg);
+ browser.runtime.sendMessage("msg from child");
+ });
+ browser.test.sendMessage("sendMessage callback called");
+ }
+
+ let extensionData = {
+ background,
+ files: {
+ "lastScript.js": lastScript,
+ "extensionpage.html": `<!DOCTYPE html><meta charset="utf-8"><script src="lastScript.js"></script>`,
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+
+ yield extension.awaitMessage("sendMessage callback called");
+ extension.sendMessage("sendMessage with a listener in another frame");
+ yield extension.awaitFinish("sendMessage did not call same-frame onMessage");
+
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js
new file mode 100644
index 000000000..d838be5b5
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js
@@ -0,0 +1,1427 @@
+"use strict";
+
+Components.utils.import("resource://gre/modules/Schemas.jsm");
+Components.utils.import("resource://gre/modules/BrowserUtils.jsm");
+Components.utils.import("resource://gre/modules/ExtensionCommon.jsm");
+
+let {LocalAPIImplementation, SchemaAPIInterface} = ExtensionCommon;
+
+let json = [
+ {namespace: "testing",
+
+ properties: {
+ PROP1: {value: 20},
+ prop2: {type: "string"},
+ prop3: {
+ $ref: "submodule",
+ },
+ prop4: {
+ $ref: "submodule",
+ unsupported: true,
+ },
+ },
+
+ types: [
+ {
+ id: "type1",
+ type: "string",
+ "enum": ["value1", "value2", "value3"],
+ },
+
+ {
+ id: "type2",
+ type: "object",
+ properties: {
+ prop1: {type: "integer"},
+ prop2: {type: "array", items: {"$ref": "type1"}},
+ },
+ },
+
+ {
+ id: "basetype1",
+ type: "object",
+ properties: {
+ prop1: {type: "string"},
+ },
+ },
+
+ {
+ id: "basetype2",
+ choices: [
+ {type: "integer"},
+ ],
+ },
+
+ {
+ $extend: "basetype1",
+ properties: {
+ prop2: {type: "string"},
+ },
+ },
+
+ {
+ $extend: "basetype2",
+ choices: [
+ {type: "string"},
+ ],
+ },
+
+ {
+ id: "submodule",
+ type: "object",
+ functions: [
+ {
+ name: "sub_foo",
+ type: "function",
+ parameters: [],
+ returns: "integer",
+ },
+ ],
+ },
+ ],
+
+ functions: [
+ {
+ name: "foo",
+ type: "function",
+ parameters: [
+ {name: "arg1", type: "integer", optional: true, default: 99},
+ {name: "arg2", type: "boolean", optional: true},
+ ],
+ },
+
+ {
+ name: "bar",
+ type: "function",
+ parameters: [
+ {name: "arg1", type: "integer", optional: true},
+ {name: "arg2", type: "boolean"},
+ ],
+ },
+
+ {
+ name: "baz",
+ type: "function",
+ parameters: [
+ {name: "arg1", type: "object", properties: {
+ prop1: {type: "string"},
+ prop2: {type: "integer", optional: true},
+ prop3: {type: "integer", unsupported: true},
+ }},
+ ],
+ },
+
+ {
+ name: "qux",
+ type: "function",
+ parameters: [
+ {name: "arg1", "$ref": "type1"},
+ ],
+ },
+
+ {
+ name: "quack",
+ type: "function",
+ parameters: [
+ {name: "arg1", "$ref": "type2"},
+ ],
+ },
+
+ {
+ name: "quora",
+ type: "function",
+ parameters: [
+ {name: "arg1", type: "function"},
+ ],
+ },
+
+ {
+ name: "quileute",
+ type: "function",
+ parameters: [
+ {name: "arg1", type: "integer", optional: true},
+ {name: "arg2", type: "integer"},
+ ],
+ },
+
+ {
+ name: "queets",
+ type: "function",
+ unsupported: true,
+ parameters: [],
+ },
+
+ {
+ name: "quintuplets",
+ type: "function",
+ parameters: [
+ {name: "obj", type: "object", properties: [], additionalProperties: {type: "integer"}},
+ ],
+ },
+
+ {
+ name: "quasar",
+ type: "function",
+ parameters: [
+ {name: "abc", type: "object", properties: {
+ func: {type: "function", parameters: [
+ {name: "x", type: "integer"},
+ ]},
+ }},
+ ],
+ },
+
+ {
+ name: "quosimodo",
+ type: "function",
+ parameters: [
+ {name: "xyz", type: "object", additionalProperties: {type: "any"}},
+ ],
+ },
+
+ {
+ name: "patternprop",
+ type: "function",
+ parameters: [
+ {
+ name: "obj",
+ type: "object",
+ properties: {"prop1": {type: "string", pattern: "^\\d+$"}},
+ patternProperties: {
+ "(?i)^prop\\d+$": {type: "string"},
+ "^foo\\d+$": {type: "string"},
+ },
+ },
+ ],
+ },
+
+ {
+ name: "pattern",
+ type: "function",
+ parameters: [
+ {name: "arg", type: "string", pattern: "(?i)^[0-9a-f]+$"},
+ ],
+ },
+
+ {
+ name: "format",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ url: {type: "string", "format": "url", "optional": true},
+ relativeUrl: {type: "string", "format": "relativeUrl", "optional": true},
+ strictRelativeUrl: {type: "string", "format": "strictRelativeUrl", "optional": true},
+ },
+ },
+ ],
+ },
+
+ {
+ name: "formatDate",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ date: {type: "string", format: "date", optional: true},
+ },
+ },
+ ],
+ },
+
+ {
+ name: "deep",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ foo: {
+ type: "object",
+ properties: {
+ bar: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ baz: {
+ type: "object",
+ properties: {
+ required: {type: "integer"},
+ optional: {type: "string", optional: true},
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+
+ {
+ name: "errors",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ warn: {
+ type: "string",
+ pattern: "^\\d+$",
+ optional: true,
+ onError: "warn",
+ },
+ ignore: {
+ type: "string",
+ pattern: "^\\d+$",
+ optional: true,
+ onError: "ignore",
+ },
+ default: {
+ type: "string",
+ pattern: "^\\d+$",
+ optional: true,
+ },
+ },
+ },
+ ],
+ },
+
+ {
+ name: "localize",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ foo: {type: "string", "preprocess": "localize", "optional": true},
+ bar: {type: "string", "optional": true},
+ url: {type: "string", "preprocess": "localize", "format": "url", "optional": true},
+ },
+ },
+ ],
+ },
+
+ {
+ name: "extended1",
+ type: "function",
+ parameters: [
+ {name: "val", $ref: "basetype1"},
+ ],
+ },
+
+ {
+ name: "extended2",
+ type: "function",
+ parameters: [
+ {name: "val", $ref: "basetype2"},
+ ],
+ },
+ ],
+
+ events: [
+ {
+ name: "onFoo",
+ type: "function",
+ },
+
+ {
+ name: "onBar",
+ type: "function",
+ extraParameters: [{
+ name: "filter",
+ type: "integer",
+ optional: true,
+ default: 1,
+ }],
+ },
+ ],
+ },
+ {
+ namespace: "foreign",
+ properties: {
+ foreignRef: {$ref: "testing.submodule"},
+ },
+ },
+ {
+ namespace: "inject",
+ properties: {
+ PROP1: {value: "should inject"},
+ },
+ },
+ {
+ namespace: "do-not-inject",
+ properties: {
+ PROP1: {value: "should not inject"},
+ },
+ },
+];
+
+let tallied = null;
+
+function tally(kind, ns, name, args) {
+ tallied = [kind, ns, name, args];
+}
+
+function verify(...args) {
+ do_check_eq(JSON.stringify(tallied), JSON.stringify(args));
+ tallied = null;
+}
+
+let talliedErrors = [];
+
+function checkErrors(errors) {
+ do_check_eq(talliedErrors.length, errors.length, "Got expected number of errors");
+ for (let [i, error] of errors.entries()) {
+ do_check_true(i in talliedErrors && talliedErrors[i].includes(error),
+ `${JSON.stringify(error)} is a substring of error ${JSON.stringify(talliedErrors[i])}`);
+ }
+
+ talliedErrors.length = 0;
+}
+
+let permissions = new Set();
+
+class TallyingAPIImplementation extends SchemaAPIInterface {
+ constructor(namespace, name) {
+ super();
+ this.namespace = namespace;
+ this.name = name;
+ }
+
+ callFunction(args) {
+ tally("call", this.namespace, this.name, args);
+ }
+
+ callFunctionNoReturn(args) {
+ tally("call", this.namespace, this.name, args);
+ }
+
+ getProperty() {
+ tally("get", this.namespace, this.name);
+ }
+
+ setProperty(value) {
+ tally("set", this.namespace, this.name, value);
+ }
+
+ addListener(listener, args) {
+ tally("addListener", this.namespace, this.name, [listener, args]);
+ }
+
+ removeListener(listener) {
+ tally("removeListener", this.namespace, this.name, [listener]);
+ }
+
+ hasListener(listener) {
+ tally("hasListener", this.namespace, this.name, [listener]);
+ }
+}
+
+let wrapper = {
+ url: "moz-extension://b66e3509-cdb3-44f6-8eb8-c8b39b3a1d27/",
+
+ checkLoadURL(url) {
+ return !url.startsWith("chrome:");
+ },
+
+ preprocessors: {
+ localize(value, context) {
+ return value.replace(/__MSG_(.*?)__/g, (m0, m1) => `${m1.toUpperCase()}`);
+ },
+ },
+
+ logError(message) {
+ talliedErrors.push(message);
+ },
+
+ hasPermission(permission) {
+ return permissions.has(permission);
+ },
+
+ shouldInject(ns) {
+ return ns != "do-not-inject";
+ },
+
+ getImplementation(namespace, name) {
+ return new TallyingAPIImplementation(namespace, name);
+ },
+};
+
+add_task(function* () {
+ let url = "data:," + JSON.stringify(json);
+ yield Schemas.load(url);
+
+ let root = {};
+ tallied = null;
+ Schemas.inject(root, wrapper);
+ do_check_eq(tallied, null);
+
+ do_check_eq(root.testing.PROP1, 20, "simple value property");
+ do_check_eq(root.testing.type1.VALUE1, "value1", "enum type");
+ do_check_eq(root.testing.type1.VALUE2, "value2", "enum type");
+
+ do_check_eq("inject" in root, true, "namespace 'inject' should be injected");
+ do_check_eq("do-not-inject" in root, false, "namespace 'do-not-inject' should not be injected");
+
+ root.testing.foo(11, true);
+ verify("call", "testing", "foo", [11, true]);
+
+ root.testing.foo(true);
+ verify("call", "testing", "foo", [99, true]);
+
+ root.testing.foo(null, true);
+ verify("call", "testing", "foo", [99, true]);
+
+ root.testing.foo(undefined, true);
+ verify("call", "testing", "foo", [99, true]);
+
+ root.testing.foo(11);
+ verify("call", "testing", "foo", [11, null]);
+
+ Assert.throws(() => root.testing.bar(11),
+ /Incorrect argument types/,
+ "should throw without required arg");
+
+ Assert.throws(() => root.testing.bar(11, true, 10),
+ /Incorrect argument types/,
+ "should throw with too many arguments");
+
+ root.testing.bar(true);
+ verify("call", "testing", "bar", [null, true]);
+
+ root.testing.baz({prop1: "hello", prop2: 22});
+ verify("call", "testing", "baz", [{prop1: "hello", prop2: 22}]);
+
+ root.testing.baz({prop1: "hello"});
+ verify("call", "testing", "baz", [{prop1: "hello", prop2: null}]);
+
+ root.testing.baz({prop1: "hello", prop2: null});
+ verify("call", "testing", "baz", [{prop1: "hello", prop2: null}]);
+
+ Assert.throws(() => root.testing.baz({prop2: 12}),
+ /Property "prop1" is required/,
+ "should throw without required property");
+
+ Assert.throws(() => root.testing.baz({prop1: "hi", prop3: 12}),
+ /Property "prop3" is unsupported by Firefox/,
+ "should throw with unsupported property");
+
+ Assert.throws(() => root.testing.baz({prop1: "hi", prop4: 12}),
+ /Unexpected property "prop4"/,
+ "should throw with unexpected property");
+
+ Assert.throws(() => root.testing.baz({prop1: 12}),
+ /Expected string instead of 12/,
+ "should throw with wrong type");
+
+ root.testing.qux("value2");
+ verify("call", "testing", "qux", ["value2"]);
+
+ Assert.throws(() => root.testing.qux("value4"),
+ /Invalid enumeration value "value4"/,
+ "should throw for invalid enum value");
+
+ root.testing.quack({prop1: 12, prop2: ["value1", "value3"]});
+ verify("call", "testing", "quack", [{prop1: 12, prop2: ["value1", "value3"]}]);
+
+ Assert.throws(() => root.testing.quack({prop1: 12, prop2: ["value1", "value3", "value4"]}),
+ /Invalid enumeration value "value4"/,
+ "should throw for invalid array type");
+
+ function f() {}
+ root.testing.quora(f);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quora"]));
+ do_check_eq(tallied[3][0], f);
+ tallied = null;
+
+ let g = () => 0;
+ root.testing.quora(g);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quora"]));
+ do_check_eq(tallied[3][0], g);
+ tallied = null;
+
+ root.testing.quileute(10);
+ verify("call", "testing", "quileute", [null, 10]);
+
+ Assert.throws(() => root.testing.queets(),
+ /queets is not a function/,
+ "should throw for unsupported functions");
+
+ root.testing.quintuplets({a: 10, b: 20, c: 30});
+ verify("call", "testing", "quintuplets", [{a: 10, b: 20, c: 30}]);
+
+ Assert.throws(() => root.testing.quintuplets({a: 10, b: 20, c: 30, d: "hi"}),
+ /Expected integer instead of "hi"/,
+ "should throw for wrong additionalProperties type");
+
+ root.testing.quasar({func: f});
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quasar"]));
+ do_check_eq(tallied[3][0].func, f);
+ tallied = null;
+
+ root.testing.quosimodo({a: 10, b: 20, c: 30});
+ verify("call", "testing", "quosimodo", [{a: 10, b: 20, c: 30}]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.quosimodo(10),
+ /Incorrect argument types/,
+ "should throw for wrong type");
+
+ root.testing.patternprop({prop1: "12", prop2: "42", Prop3: "43", foo1: "x"});
+ verify("call", "testing", "patternprop", [{prop1: "12", prop2: "42", Prop3: "43", foo1: "x"}]);
+ tallied = null;
+
+ root.testing.patternprop({prop1: "12"});
+ verify("call", "testing", "patternprop", [{prop1: "12"}]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.patternprop({prop1: "12", foo1: null}),
+ /Expected string instead of null/,
+ "should throw for wrong property type");
+
+ Assert.throws(() => root.testing.patternprop({prop1: "xx", prop2: "yy"}),
+ /String "xx" must match \/\^\\d\+\$\//,
+ "should throw for wrong property type");
+
+ Assert.throws(() => root.testing.patternprop({prop1: "12", prop2: 42}),
+ /Expected string instead of 42/,
+ "should throw for wrong property type");
+
+ Assert.throws(() => root.testing.patternprop({prop1: "12", prop2: null}),
+ /Expected string instead of null/,
+ "should throw for wrong property type");
+
+ Assert.throws(() => root.testing.patternprop({prop1: "12", propx: "42"}),
+ /Unexpected property "propx"/,
+ "should throw for unexpected property");
+
+ Assert.throws(() => root.testing.patternprop({prop1: "12", Foo1: "x"}),
+ /Unexpected property "Foo1"/,
+ "should throw for unexpected property");
+
+ root.testing.pattern("DEADbeef");
+ verify("call", "testing", "pattern", ["DEADbeef"]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.pattern("DEADcow"),
+ /String "DEADcow" must match \/\^\[0-9a-f\]\+\$\/i/,
+ "should throw for non-match");
+
+ root.testing.format({url: "http://foo/bar",
+ relativeUrl: "http://foo/bar"});
+ verify("call", "testing", "format", [{url: "http://foo/bar",
+ relativeUrl: "http://foo/bar",
+ strictRelativeUrl: null}]);
+ tallied = null;
+
+ root.testing.format({relativeUrl: "foo.html", strictRelativeUrl: "foo.html"});
+ verify("call", "testing", "format", [{url: null,
+ relativeUrl: `${wrapper.url}foo.html`,
+ strictRelativeUrl: `${wrapper.url}foo.html`}]);
+ tallied = null;
+
+ for (let format of ["url", "relativeUrl"]) {
+ Assert.throws(() => root.testing.format({[format]: "chrome://foo/content/"}),
+ /Access denied/,
+ "should throw for access denied");
+ }
+
+ for (let urlString of ["//foo.html", "http://foo/bar.html"]) {
+ Assert.throws(() => root.testing.format({strictRelativeUrl: urlString}),
+ /must be a relative URL/,
+ "should throw for non-relative URL");
+ }
+
+ const dates = [
+ "2016-03-04",
+ "2016-03-04T08:00:00Z",
+ "2016-03-04T08:00:00.000Z",
+ "2016-03-04T08:00:00-08:00",
+ "2016-03-04T08:00:00.000-08:00",
+ "2016-03-04T08:00:00+08:00",
+ "2016-03-04T08:00:00.000+08:00",
+ "2016-03-04T08:00:00+0800",
+ "2016-03-04T08:00:00-0800",
+ ];
+ dates.forEach(str => {
+ root.testing.formatDate({date: str});
+ verify("call", "testing", "formatDate", [{date: str}]);
+ });
+
+ // Make sure that a trivial change to a valid date invalidates it.
+ dates.forEach(str => {
+ Assert.throws(() => root.testing.formatDate({date: "0" + str}),
+ /Invalid date string/,
+ "should throw for invalid iso date string");
+ Assert.throws(() => root.testing.formatDate({date: str + "0"}),
+ /Invalid date string/,
+ "should throw for invalid iso date string");
+ });
+
+ const badDates = [
+ "I do not look anything like a date string",
+ "2016-99-99",
+ "2016-03-04T25:00:00Z",
+ ];
+ badDates.forEach(str => {
+ Assert.throws(() => root.testing.formatDate({date: str}),
+ /Invalid date string/,
+ "should throw for invalid iso date string");
+ });
+
+ root.testing.deep({foo: {bar: [{baz: {required: 12, optional: "42"}}]}});
+ verify("call", "testing", "deep", [{foo: {bar: [{baz: {required: 12, optional: "42"}}]}}]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.deep({foo: {bar: [{baz: {optional: "42"}}]}}),
+ /Type error for parameter arg \(Error processing foo\.bar\.0\.baz: Property "required" is required\) for testing\.deep/,
+ "should throw with the correct object path");
+
+ Assert.throws(() => root.testing.deep({foo: {bar: [{baz: {required: 12, optional: 42}}]}}),
+ /Type error for parameter arg \(Error processing foo\.bar\.0\.baz\.optional: Expected string instead of 42\) for testing\.deep/,
+ "should throw with the correct object path");
+
+
+ talliedErrors.length = 0;
+
+ root.testing.errors({warn: "0123", ignore: "0123", default: "0123"});
+ verify("call", "testing", "errors", [{warn: "0123", ignore: "0123", default: "0123"}]);
+ checkErrors([]);
+
+ root.testing.errors({warn: "0123", ignore: "x123", default: "0123"});
+ verify("call", "testing", "errors", [{warn: "0123", ignore: null, default: "0123"}]);
+ checkErrors([]);
+
+ root.testing.errors({warn: "x123", ignore: "0123", default: "0123"});
+ verify("call", "testing", "errors", [{warn: null, ignore: "0123", default: "0123"}]);
+ checkErrors([
+ 'String "x123" must match /^\\d+$/',
+ ]);
+
+
+ root.testing.onFoo.addListener(f);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onFoo"]));
+ do_check_eq(tallied[3][0], f);
+ do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([]));
+ tallied = null;
+
+ root.testing.onFoo.removeListener(f);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["removeListener", "testing", "onFoo"]));
+ do_check_eq(tallied[3][0], f);
+ tallied = null;
+
+ root.testing.onFoo.hasListener(f);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["hasListener", "testing", "onFoo"]));
+ do_check_eq(tallied[3][0], f);
+ tallied = null;
+
+ Assert.throws(() => root.testing.onFoo.addListener(10),
+ /Invalid listener/,
+ "addListener with non-function should throw");
+
+ root.testing.onBar.addListener(f, 10);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onBar"]));
+ do_check_eq(tallied[3][0], f);
+ do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([10]));
+ tallied = null;
+
+ root.testing.onBar.addListener(f);
+ do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onBar"]));
+ do_check_eq(tallied[3][0], f);
+ do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([1]));
+ tallied = null;
+
+ Assert.throws(() => root.testing.onBar.addListener(f, "hi"),
+ /Incorrect argument types/,
+ "addListener with wrong extra parameter should throw");
+
+ let target = {prop1: 12, prop2: ["value1", "value3"]};
+ let proxy = new Proxy(target, {});
+ Assert.throws(() => root.testing.quack(proxy),
+ /Expected a plain JavaScript object, got a Proxy/,
+ "should throw when passing a Proxy");
+
+ if (Symbol.toStringTag) {
+ let stringTarget = {prop1: 12, prop2: ["value1", "value3"]};
+ stringTarget[Symbol.toStringTag] = () => "[object Object]";
+ let stringProxy = new Proxy(stringTarget, {});
+ Assert.throws(() => root.testing.quack(stringProxy),
+ /Expected a plain JavaScript object, got a Proxy/,
+ "should throw when passing a Proxy");
+ }
+
+
+ root.testing.localize({foo: "__MSG_foo__", bar: "__MSG_foo__", url: "__MSG_http://example.com/__"});
+ verify("call", "testing", "localize", [{foo: "FOO", bar: "__MSG_foo__", url: "http://example.com/"}]);
+ tallied = null;
+
+
+ Assert.throws(() => root.testing.localize({url: "__MSG_/foo/bar__"}),
+ /\/FOO\/BAR is not a valid URL\./,
+ "should throw for invalid URL");
+
+
+ root.testing.extended1({prop1: "foo", prop2: "bar"});
+ verify("call", "testing", "extended1", [{prop1: "foo", prop2: "bar"}]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.extended1({prop1: "foo", prop2: 12}),
+ /Expected string instead of 12/,
+ "should throw for wrong property type");
+
+ Assert.throws(() => root.testing.extended1({prop1: "foo"}),
+ /Property "prop2" is required/,
+ "should throw for missing property");
+
+ Assert.throws(() => root.testing.extended1({prop1: "foo", prop2: "bar", prop3: "xxx"}),
+ /Unexpected property "prop3"/,
+ "should throw for extra property");
+
+
+ root.testing.extended2("foo");
+ verify("call", "testing", "extended2", ["foo"]);
+ tallied = null;
+
+ root.testing.extended2(12);
+ verify("call", "testing", "extended2", [12]);
+ tallied = null;
+
+ Assert.throws(() => root.testing.extended2(true),
+ /Incorrect argument types/,
+ "should throw for wrong argument type");
+
+ root.testing.prop3.sub_foo();
+ verify("call", "testing.prop3", "sub_foo", []);
+ tallied = null;
+
+ Assert.throws(() => root.testing.prop4.sub_foo(),
+ /root.testing.prop4 is undefined/,
+ "should throw for unsupported submodule");
+
+ root.foreign.foreignRef.sub_foo();
+ verify("call", "foreign.foreignRef", "sub_foo", []);
+ tallied = null;
+});
+
+let deprecatedJson = [
+ {namespace: "deprecated",
+
+ properties: {
+ accessor: {
+ type: "string",
+ writable: true,
+ deprecated: "This is not the property you are looking for",
+ },
+ },
+
+ types: [
+ {
+ "id": "Type",
+ "type": "string",
+ },
+ ],
+
+ functions: [
+ {
+ name: "property",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ type: "object",
+ properties: {
+ foo: {
+ type: "string",
+ },
+ },
+ additionalProperties: {
+ type: "any",
+ deprecated: "Unknown property",
+ },
+ },
+ ],
+ },
+
+ {
+ name: "value",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ choices: [
+ {
+ type: "integer",
+ },
+ {
+ type: "string",
+ deprecated: "Please use an integer, not ${value}",
+ },
+ ],
+ },
+ ],
+ },
+
+ {
+ name: "choices",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ deprecated: "You have no choices",
+ choices: [
+ {
+ type: "integer",
+ },
+ ],
+ },
+ ],
+ },
+
+ {
+ name: "ref",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ choices: [
+ {
+ $ref: "Type",
+ deprecated: "Deprecated alias",
+ },
+ ],
+ },
+ ],
+ },
+
+ {
+ name: "method",
+ type: "function",
+ deprecated: "Do not call this method",
+ parameters: [
+ ],
+ },
+ ],
+
+ events: [
+ {
+ name: "onDeprecated",
+ type: "function",
+ deprecated: "This event does not work",
+ },
+ ],
+ },
+];
+
+add_task(function* testDeprecation() {
+ let url = "data:," + JSON.stringify(deprecatedJson);
+ yield Schemas.load(url);
+
+ let root = {};
+ Schemas.inject(root, wrapper);
+
+ talliedErrors.length = 0;
+
+
+ root.deprecated.property({foo: "bar", xxx: "any", yyy: "property"});
+ verify("call", "deprecated", "property", [{foo: "bar", xxx: "any", yyy: "property"}]);
+ checkErrors([
+ "Error processing xxx: Unknown property",
+ "Error processing yyy: Unknown property",
+ ]);
+
+ root.deprecated.value(12);
+ verify("call", "deprecated", "value", [12]);
+ checkErrors([]);
+
+ root.deprecated.value("12");
+ verify("call", "deprecated", "value", ["12"]);
+ checkErrors(["Please use an integer, not \"12\""]);
+
+ root.deprecated.choices(12);
+ verify("call", "deprecated", "choices", [12]);
+ checkErrors(["You have no choices"]);
+
+ root.deprecated.ref("12");
+ verify("call", "deprecated", "ref", ["12"]);
+ checkErrors(["Deprecated alias"]);
+
+ root.deprecated.method();
+ verify("call", "deprecated", "method", []);
+ checkErrors(["Do not call this method"]);
+
+
+ void root.deprecated.accessor;
+ verify("get", "deprecated", "accessor", null);
+ checkErrors(["This is not the property you are looking for"]);
+
+ root.deprecated.accessor = "x";
+ verify("set", "deprecated", "accessor", "x");
+ checkErrors(["This is not the property you are looking for"]);
+
+
+ root.deprecated.onDeprecated.addListener(() => {});
+ checkErrors(["This event does not work"]);
+
+ root.deprecated.onDeprecated.removeListener(() => {});
+ checkErrors(["This event does not work"]);
+
+ root.deprecated.onDeprecated.hasListener(() => {});
+ checkErrors(["This event does not work"]);
+});
+
+
+let choicesJson = [
+ {namespace: "choices",
+
+ types: [
+ ],
+
+ functions: [
+ {
+ name: "meh",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ choices: [
+ {
+ type: "string",
+ enum: ["foo", "bar", "baz"],
+ },
+ {
+ type: "string",
+ pattern: "florg.*meh",
+ },
+ {
+ type: "integer",
+ minimum: 12,
+ maximum: 42,
+ },
+ ],
+ },
+ ],
+ },
+
+ {
+ name: "foo",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ choices: [
+ {
+ type: "object",
+ properties: {
+ blurg: {
+ type: "string",
+ unsupported: true,
+ optional: true,
+ },
+ },
+ additionalProperties: {
+ type: "string",
+ },
+ },
+ {
+ type: "string",
+ },
+ {
+ type: "array",
+ minItems: 2,
+ maxItems: 3,
+ items: {
+ type: "integer",
+ },
+ },
+ ],
+ },
+ ],
+ },
+
+ {
+ name: "bar",
+ type: "function",
+ parameters: [
+ {
+ name: "arg",
+ choices: [
+ {
+ type: "object",
+ properties: {
+ baz: {
+ type: "string",
+ },
+ },
+ },
+ {
+ type: "array",
+ items: {
+ type: "integer",
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ]},
+];
+
+add_task(function* testChoices() {
+ let url = "data:," + JSON.stringify(choicesJson);
+ yield Schemas.load(url);
+
+ let root = {};
+ Schemas.inject(root, wrapper);
+
+ talliedErrors.length = 0;
+
+ Assert.throws(() => root.choices.meh("frog"),
+ /Value must either: be one of \["foo", "bar", "baz"\], match the pattern \/florg\.\*meh\/, or be an integer value/);
+
+ Assert.throws(() => root.choices.meh(4),
+ /be a string value, or be at least 12/);
+
+ Assert.throws(() => root.choices.meh(43),
+ /be a string value, or be no greater than 42/);
+
+
+ Assert.throws(() => root.choices.foo([]),
+ /be an object value, be a string value, or have at least 2 items/);
+
+ Assert.throws(() => root.choices.foo([1, 2, 3, 4]),
+ /be an object value, be a string value, or have at most 3 items/);
+
+ Assert.throws(() => root.choices.foo({foo: 12}),
+ /.foo must be a string value, be a string value, or be an array value/);
+
+ Assert.throws(() => root.choices.foo({blurg: "foo"}),
+ /not contain an unsupported "blurg" property, be a string value, or be an array value/);
+
+
+ Assert.throws(() => root.choices.bar({}),
+ /contain the required "baz" property, or be an array value/);
+
+ Assert.throws(() => root.choices.bar({baz: "x", quux: "y"}),
+ /not contain an unexpected "quux" property, or be an array value/);
+
+ Assert.throws(() => root.choices.bar({baz: "x", quux: "y", foo: "z"}),
+ /not contain the unexpected properties \[foo, quux\], or be an array value/);
+});
+
+
+let permissionsJson = [
+ {namespace: "noPerms",
+
+ types: [],
+
+ functions: [
+ {
+ name: "noPerms",
+ type: "function",
+ parameters: [],
+ },
+
+ {
+ name: "fooPerm",
+ type: "function",
+ permissions: ["foo"],
+ parameters: [],
+ },
+ ]},
+
+ {namespace: "fooPerm",
+
+ permissions: ["foo"],
+
+ types: [],
+
+ functions: [
+ {
+ name: "noPerms",
+ type: "function",
+ parameters: [],
+ },
+
+ {
+ name: "fooBarPerm",
+ type: "function",
+ permissions: ["foo.bar"],
+ parameters: [],
+ },
+ ]},
+];
+
+add_task(function* testPermissions() {
+ let url = "data:," + JSON.stringify(permissionsJson);
+ yield Schemas.load(url);
+
+ let root = {};
+ Schemas.inject(root, wrapper);
+
+ equal(typeof root.noPerms, "object", "noPerms namespace should exist");
+ equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist");
+
+ ok(!("fooPerm" in root.noPerms), "noPerms.fooPerm should not method exist");
+
+ ok(!("fooPerm" in root), "fooPerm namespace should not exist");
+
+
+ do_print('Add "foo" permission');
+ permissions.add("foo");
+
+ root = {};
+ Schemas.inject(root, wrapper);
+
+ equal(typeof root.noPerms, "object", "noPerms namespace should exist");
+ equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist");
+ equal(typeof root.noPerms.fooPerm, "function", "noPerms.fooPerm method should exist");
+
+ equal(typeof root.fooPerm, "object", "fooPerm namespace should exist");
+ equal(typeof root.fooPerm.noPerms, "function", "noPerms.noPerms method should exist");
+
+ ok(!("fooBarPerm" in root.fooPerm), "fooPerm.fooBarPerm method should not exist");
+
+
+ do_print('Add "foo.bar" permission');
+ permissions.add("foo.bar");
+
+ root = {};
+ Schemas.inject(root, wrapper);
+
+ equal(typeof root.noPerms, "object", "noPerms namespace should exist");
+ equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist");
+ equal(typeof root.noPerms.fooPerm, "function", "noPerms.fooPerm method should exist");
+
+ equal(typeof root.fooPerm, "object", "fooPerm namespace should exist");
+ equal(typeof root.fooPerm.noPerms, "function", "noPerms.noPerms method should exist");
+ equal(typeof root.fooPerm.fooBarPerm, "function", "noPerms.fooBarPerm method should exist");
+});
+
+let nestedNamespaceJson = [
+ {
+ "namespace": "nested.namespace",
+ "types": [
+ {
+ "id": "CustomType",
+ "type": "object",
+ "events": [
+ {
+ "name": "onEvent",
+ },
+ ],
+ "properties": {
+ "url": {
+ "type": "string",
+ },
+ },
+ "functions": [
+ {
+ "name": "functionOnCustomType",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "title",
+ "type": "string",
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ "properties": {
+ "instanceOfCustomType": {
+ "$ref": "CustomType",
+ },
+ },
+ "functions": [
+ {
+ "name": "create",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "title",
+ "type": "string",
+ },
+ ],
+ },
+ ],
+ },
+];
+
+add_task(function* testNestedNamespace() {
+ let url = "data:," + JSON.stringify(nestedNamespaceJson);
+
+ yield Schemas.load(url);
+
+ let root = {};
+ Schemas.inject(root, wrapper);
+
+ talliedErrors.length = 0;
+
+ ok(root.nested, "The root object contains the first namespace level");
+ ok(root.nested.namespace, "The first level object contains the second namespace level");
+
+ ok(root.nested.namespace.create, "Got the expected function in the nested namespace");
+ do_check_eq(typeof root.nested.namespace.create, "function",
+ "The property is a function as expected");
+
+ let {instanceOfCustomType} = root.nested.namespace;
+
+ ok(instanceOfCustomType,
+ "Got the expected instance of the CustomType defined in the schema");
+ ok(instanceOfCustomType.functionOnCustomType,
+ "Got the expected method in the CustomType instance");
+
+ // TODO: test support events and properties in a SubModuleType defined in the schema,
+ // once implemented, e.g.:
+ //
+ // ok(instanceOfCustomType.url,
+ // "Got the expected property defined in the CustomType instance)
+ //
+ // ok(instanceOfCustomType.onEvent &&
+ // instanceOfCustomType.onEvent.addListener &&
+ // typeof instanceOfCustomType.onEvent.addListener == "function",
+ // "Got the expected event defined in the CustomType instance");
+});
+
+add_task(function* testLocalAPIImplementation() {
+ let countGet2 = 0;
+ let countProp3 = 0;
+ let countProp3SubFoo = 0;
+
+ let testingApiObj = {
+ get PROP1() {
+ // PROP1 is a schema-defined constant.
+ throw new Error("Unexpected get PROP1");
+ },
+ get prop2() {
+ ++countGet2;
+ return "prop2 val";
+ },
+ get prop3() {
+ throw new Error("Unexpected get prop3");
+ },
+ set prop3(v) {
+ // prop3 is a submodule, defined as a function, so the API should not pass
+ // through assignment to prop3.
+ throw new Error("Unexpected set prop3");
+ },
+ };
+ let submoduleApiObj = {
+ get sub_foo() {
+ ++countProp3;
+ return () => {
+ return ++countProp3SubFoo;
+ };
+ },
+ };
+
+ let localWrapper = {
+ shouldInject(ns) {
+ return ns == "testing" || ns == "testing.prop3";
+ },
+ getImplementation(ns, name) {
+ do_check_true(ns == "testing" || ns == "testing.prop3");
+ if (ns == "testing.prop3" && name == "sub_foo") {
+ // It is fine to use `null` here because we don't call async functions.
+ return new LocalAPIImplementation(submoduleApiObj, name, null);
+ }
+ // It is fine to use `null` here because we don't call async functions.
+ return new LocalAPIImplementation(testingApiObj, name, null);
+ },
+ };
+
+ let root = {};
+ Schemas.inject(root, localWrapper);
+ do_check_eq(countGet2, 0);
+ do_check_eq(countProp3, 0);
+ do_check_eq(countProp3SubFoo, 0);
+
+ do_check_eq(root.testing.PROP1, 20);
+
+ do_check_eq(root.testing.prop2, "prop2 val");
+ do_check_eq(countGet2, 1);
+
+ do_check_eq(root.testing.prop2, "prop2 val");
+ do_check_eq(countGet2, 2);
+
+ do_print(JSON.stringify(root.testing));
+ do_check_eq(root.testing.prop3.sub_foo(), 1);
+ do_check_eq(countProp3, 1);
+ do_check_eq(countProp3SubFoo, 1);
+
+ do_check_eq(root.testing.prop3.sub_foo(), 2);
+ do_check_eq(countProp3, 2);
+ do_check_eq(countProp3SubFoo, 2);
+
+ root.testing.prop3.sub_foo = () => { return "overwritten"; };
+ do_check_eq(root.testing.prop3.sub_foo(), "overwritten");
+
+ root.testing.prop3 = {sub_foo() { return "overwritten again"; }};
+ do_check_eq(root.testing.prop3.sub_foo(), "overwritten again");
+ do_check_eq(countProp3SubFoo, 2);
+});
+
+
+let defaultsJson = [
+ {namespace: "defaultsJson",
+
+ types: [],
+
+ functions: [
+ {
+ name: "defaultFoo",
+ type: "function",
+ parameters: [
+ {name: "arg", type: "object", optional: true, properties: {
+ prop1: {type: "integer", optional: true},
+ }, default: {prop1: 1}},
+ ],
+ returns: {
+ type: "object",
+ },
+ },
+ ]},
+];
+
+add_task(function* testDefaults() {
+ let url = "data:," + JSON.stringify(defaultsJson);
+ yield Schemas.load(url);
+
+ let testingApiObj = {
+ defaultFoo: function(arg) {
+ if (Object.keys(arg) != "prop1") {
+ throw new Error(`Received the expected default object, default: ${JSON.stringify(arg)}`);
+ }
+ arg.newProp = 1;
+ return arg;
+ },
+ };
+
+ let localWrapper = {
+ shouldInject(ns) {
+ return true;
+ },
+ getImplementation(ns, name) {
+ return new LocalAPIImplementation(testingApiObj, name, null);
+ },
+ };
+
+ let root = {};
+ Schemas.inject(root, localWrapper);
+
+ deepEqual(root.defaultsJson.defaultFoo(), {prop1: 1, newProp: 1});
+ deepEqual(root.defaultsJson.defaultFoo({prop1: 2}), {prop1: 2, newProp: 1});
+ deepEqual(root.defaultsJson.defaultFoo(), {prop1: 1, newProp: 1});
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js
new file mode 100644
index 000000000..606459764
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js
@@ -0,0 +1,147 @@
+"use strict";
+
+Components.utils.import("resource://gre/modules/Schemas.jsm");
+
+let schemaJson = [
+ {
+ namespace: "noAllowedContexts",
+ properties: {
+ prop1: {type: "object"},
+ prop2: {type: "object", allowedContexts: ["test_zero", "test_one"]},
+ prop3: {type: "number", value: 1},
+ prop4: {type: "number", value: 1, allowedContexts: ["numeric_one"]},
+ },
+ },
+ {
+ namespace: "defaultContexts",
+ defaultContexts: ["test_two"],
+ properties: {
+ prop1: {type: "object"},
+ prop2: {type: "object", allowedContexts: ["test_three"]},
+ prop3: {type: "number", value: 1},
+ prop4: {type: "number", value: 1, allowedContexts: ["numeric_two"]},
+ },
+ },
+ {
+ namespace: "withAllowedContexts",
+ allowedContexts: ["test_four"],
+ properties: {
+ prop1: {type: "object"},
+ prop2: {type: "object", allowedContexts: ["test_five"]},
+ prop3: {type: "number", value: 1},
+ prop4: {type: "number", value: 1, allowedContexts: ["numeric_three"]},
+ },
+ },
+ {
+ namespace: "withAllowedContextsAndDefault",
+ allowedContexts: ["test_six"],
+ defaultContexts: ["test_seven"],
+ properties: {
+ prop1: {type: "object"},
+ prop2: {type: "object", allowedContexts: ["test_eight"]},
+ prop3: {type: "number", value: 1},
+ prop4: {type: "number", value: 1, allowedContexts: ["numeric_four"]},
+ },
+ },
+ {
+ namespace: "with_submodule",
+ defaultContexts: ["test_nine"],
+ types: [{
+ id: "subtype",
+ type: "object",
+ functions: [{
+ name: "noAllowedContexts",
+ type: "function",
+ parameters: [],
+ }, {
+ name: "allowedContexts",
+ allowedContexts: ["test_ten"],
+ type: "function",
+ parameters: [],
+ }],
+ }],
+ properties: {
+ prop1: {$ref: "subtype"},
+ prop2: {$ref: "subtype", allowedContexts: ["test_eleven"]},
+ },
+ },
+];
+add_task(function* testRestrictions() {
+ let url = "data:," + JSON.stringify(schemaJson);
+ yield Schemas.load(url);
+ let results = {};
+ let localWrapper = {
+ shouldInject(ns, name, allowedContexts) {
+ name = name === null ? ns : ns + "." + name;
+ results[name] = allowedContexts.join(",");
+ return true;
+ },
+ getImplementation() {
+ // The actual implementation is not significant for this test.
+ // Let's take this opportunity to see if schema generation is free of
+ // exceptions even when somehow getImplementation does not return an
+ // implementation.
+ },
+ };
+
+ let root = {};
+ Schemas.inject(root, localWrapper);
+
+ function verify(path, expected) {
+ let obj = root;
+ for (let thing of path.split(".")) {
+ try {
+ obj = obj[thing];
+ } catch (e) {
+ // Blech.
+ }
+ }
+
+ let result = results[path];
+ equal(result, expected);
+ }
+
+ verify("noAllowedContexts", "");
+ verify("noAllowedContexts.prop1", "");
+ verify("noAllowedContexts.prop2", "test_zero,test_one");
+ verify("noAllowedContexts.prop3", "");
+ verify("noAllowedContexts.prop4", "numeric_one");
+
+ verify("defaultContexts", "");
+ verify("defaultContexts.prop1", "test_two");
+ verify("defaultContexts.prop2", "test_three");
+ verify("defaultContexts.prop3", "test_two");
+ verify("defaultContexts.prop4", "numeric_two");
+
+ verify("withAllowedContexts", "test_four");
+ verify("withAllowedContexts.prop1", "");
+ verify("withAllowedContexts.prop2", "test_five");
+ verify("withAllowedContexts.prop3", "");
+ verify("withAllowedContexts.prop4", "numeric_three");
+
+ verify("withAllowedContextsAndDefault", "test_six");
+ verify("withAllowedContextsAndDefault.prop1", "test_seven");
+ verify("withAllowedContextsAndDefault.prop2", "test_eight");
+ verify("withAllowedContextsAndDefault.prop3", "test_seven");
+ verify("withAllowedContextsAndDefault.prop4", "numeric_four");
+
+ verify("with_submodule", "");
+ verify("with_submodule.prop1", "test_nine");
+ verify("with_submodule.prop1.noAllowedContexts", "test_nine");
+ verify("with_submodule.prop1.allowedContexts", "test_ten");
+ verify("with_submodule.prop2", "test_eleven");
+ // Note: test_nine inherits allowed contexts from the namespace, not from
+ // submodule. There is no "defaultContexts" for submodule types to not
+ // complicate things.
+ verify("with_submodule.prop1.noAllowedContexts", "test_nine");
+ verify("with_submodule.prop1.allowedContexts", "test_ten");
+
+ // This is a constant, so it does not matter that getImplementation does not
+ // return an implementation since the API injector should take care of it.
+ equal(root.noAllowedContexts.prop3, 1);
+
+ Assert.throws(() => root.noAllowedContexts.prop1,
+ /undefined/,
+ "Should throw when the implementation is absent.");
+});
+
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js
new file mode 100644
index 000000000..36d88d722
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js
@@ -0,0 +1,102 @@
+"use strict";
+
+Components.utils.import("resource://gre/modules/ExtensionCommon.jsm");
+Components.utils.import("resource://gre/modules/Schemas.jsm");
+
+let {
+ BaseContext,
+ SchemaAPIManager,
+} = ExtensionCommon;
+
+let nestedNamespaceJson = [
+ {
+ "namespace": "backgroundAPI.testnamespace",
+ "functions": [
+ {
+ "name": "create",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "title",
+ "type": "string",
+ },
+ ],
+ "returns": {
+ "type": "string",
+ },
+ },
+ ],
+ },
+ {
+ "namespace": "noBackgroundAPI.testnamespace",
+ "functions": [
+ {
+ "name": "create",
+ "type": "function",
+ "parameters": [
+ {
+ "name": "title",
+ "type": "string",
+ },
+ ],
+ },
+ ],
+ },
+];
+
+let global = this;
+class StubContext extends BaseContext {
+ constructor() {
+ let fakeExtension = {id: "test@web.extension"};
+ super("addon_child", fakeExtension);
+ this.sandbox = Cu.Sandbox(global);
+ this.viewType = "background";
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+}
+
+add_task(function* testSchemaAPIInjection() {
+ let url = "data:," + JSON.stringify(nestedNamespaceJson);
+
+ // Load the schema of the fake APIs.
+ yield Schemas.load(url);
+
+ let apiManager = new SchemaAPIManager("addon");
+
+ // Register an API that will skip the background page.
+ apiManager.registerSchemaAPI("noBackgroundAPI.testnamespace", "addon_child", context => {
+ // This API should not be available in this context, return null so that
+ // the schema wrapper is removed as well.
+ return null;
+ });
+
+ // Register an API that will skip any but the background page.
+ apiManager.registerSchemaAPI("backgroundAPI.testnamespace", "addon_child", context => {
+ if (context.viewType === "background") {
+ return {
+ backgroundAPI: {
+ testnamespace: {
+ create(title) {
+ return title;
+ },
+ },
+ },
+ };
+ }
+
+ // This API should not be available in this context, return null so that
+ // the schema wrapper is removed as well.
+ return null;
+ });
+
+ let context = new StubContext();
+ let browserObj = {};
+ apiManager.generateAPIs(context, browserObj);
+
+ do_check_eq(browserObj.noBackgroundAPI, undefined);
+ const res = browserObj.backgroundAPI.testnamespace.create("param-value");
+ do_check_eq(res, "param-value");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js
new file mode 100644
index 000000000..6397d1f96
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js
@@ -0,0 +1,232 @@
+"use strict";
+
+Components.utils.import("resource://gre/modules/ExtensionCommon.jsm");
+Components.utils.import("resource://gre/modules/Schemas.jsm");
+
+let {BaseContext, LocalAPIImplementation} = ExtensionCommon;
+
+let schemaJson = [
+ {
+ namespace: "testnamespace",
+ functions: [{
+ name: "one_required",
+ type: "function",
+ parameters: [{
+ name: "first",
+ type: "function",
+ parameters: [],
+ }],
+ }, {
+ name: "one_optional",
+ type: "function",
+ parameters: [{
+ name: "first",
+ type: "function",
+ parameters: [],
+ optional: true,
+ }],
+ }, {
+ name: "async_required",
+ type: "function",
+ async: "first",
+ parameters: [{
+ name: "first",
+ type: "function",
+ parameters: [],
+ }],
+ }, {
+ name: "async_optional",
+ type: "function",
+ async: "first",
+ parameters: [{
+ name: "first",
+ type: "function",
+ parameters: [],
+ optional: true,
+ }],
+ }],
+ },
+];
+
+const global = this;
+class StubContext extends BaseContext {
+ constructor() {
+ let fakeExtension = {id: "test@web.extension"};
+ super("testEnv", fakeExtension);
+ this.sandbox = Cu.Sandbox(global);
+ }
+
+ get cloneScope() {
+ return this.sandbox;
+ }
+
+ get principal() {
+ return Cu.getObjectPrincipal(this.sandbox);
+ }
+}
+
+let context;
+
+function generateAPIs(extraWrapper, apiObj) {
+ context = new StubContext();
+ let localWrapper = {
+ shouldInject() {
+ return true;
+ },
+ getImplementation(namespace, name) {
+ return new LocalAPIImplementation(apiObj, name, context);
+ },
+ };
+ Object.assign(localWrapper, extraWrapper);
+
+ let root = {};
+ Schemas.inject(root, localWrapper);
+ return root.testnamespace;
+}
+
+add_task(function* testParameterValidation() {
+ yield Schemas.load("data:," + JSON.stringify(schemaJson));
+
+ let testnamespace;
+ function assertThrows(name, ...args) {
+ Assert.throws(() => testnamespace[name](...args),
+ /Incorrect argument types/,
+ `Expected testnamespace.${name}(${args.map(String).join(", ")}) to throw.`);
+ }
+ function assertNoThrows(name, ...args) {
+ try {
+ testnamespace[name](...args);
+ } catch (e) {
+ do_print(`testnamespace.${name}(${args.map(String).join(", ")}) unexpectedly threw.`);
+ throw new Error(e);
+ }
+ }
+ let cb = () => {};
+
+ for (let isChromeCompat of [true, false]) {
+ do_print(`Testing API validation with isChromeCompat=${isChromeCompat}`);
+ testnamespace = generateAPIs({
+ isChromeCompat,
+ }, {
+ one_required() {},
+ one_optional() {},
+ async_required() {},
+ async_optional() {},
+ });
+
+ assertThrows("one_required");
+ assertThrows("one_required", null);
+ assertNoThrows("one_required", cb);
+ assertThrows("one_required", cb, null);
+ assertThrows("one_required", cb, cb);
+
+ assertNoThrows("one_optional");
+ assertNoThrows("one_optional", null);
+ assertNoThrows("one_optional", cb);
+ assertThrows("one_optional", cb, null);
+ assertThrows("one_optional", cb, cb);
+
+ // Schema-based validation happens before an async method is called, so
+ // errors should be thrown synchronously.
+
+ // The parameter was declared as required, but there was also an "async"
+ // attribute with the same value as the parameter name, so the callback
+ // parameter is actually optional.
+ assertNoThrows("async_required");
+ assertNoThrows("async_required", null);
+ assertNoThrows("async_required", cb);
+ assertThrows("async_required", cb, null);
+ assertThrows("async_required", cb, cb);
+
+ assertNoThrows("async_optional");
+ assertNoThrows("async_optional", null);
+ assertNoThrows("async_optional", cb);
+ assertThrows("async_optional", cb, null);
+ assertThrows("async_optional", cb, cb);
+ }
+});
+
+add_task(function* testAsyncResults() {
+ yield Schemas.load("data:," + JSON.stringify(schemaJson));
+ function* runWithCallback(func) {
+ do_print(`Calling testnamespace.${func.name}, expecting callback with result`);
+ return yield new Promise(resolve => {
+ let result = "uninitialized value";
+ let returnValue = func(reply => {
+ result = reply;
+ resolve(result);
+ });
+ // When a callback is given, the return value must be missing.
+ do_check_eq(returnValue, undefined);
+ // Callback must be called asynchronously.
+ do_check_eq(result, "uninitialized value");
+ });
+ }
+
+ function* runFailCallback(func) {
+ do_print(`Calling testnamespace.${func.name}, expecting callback with error`);
+ return yield new Promise(resolve => {
+ func(reply => {
+ do_check_eq(reply, undefined);
+ resolve(context.lastError.message); // eslint-disable-line no-undef
+ });
+ });
+ }
+
+ for (let isChromeCompat of [true, false]) {
+ do_print(`Testing API invocation with isChromeCompat=${isChromeCompat}`);
+ let testnamespace = generateAPIs({
+ isChromeCompat,
+ }, {
+ async_required(cb) {
+ do_check_eq(cb, undefined);
+ return Promise.resolve(1);
+ },
+ async_optional(cb) {
+ do_check_eq(cb, undefined);
+ return Promise.resolve(2);
+ },
+ });
+ if (!isChromeCompat) { // No promises for chrome.
+ do_print("testnamespace.async_required should be a Promise");
+ let promise = testnamespace.async_required();
+ do_check_true(promise instanceof context.cloneScope.Promise);
+ do_check_eq(yield promise, 1);
+
+ do_print("testnamespace.async_optional should be a Promise");
+ promise = testnamespace.async_optional();
+ do_check_true(promise instanceof context.cloneScope.Promise);
+ do_check_eq(yield promise, 2);
+ }
+
+ do_check_eq(yield* runWithCallback(testnamespace.async_required), 1);
+ do_check_eq(yield* runWithCallback(testnamespace.async_optional), 2);
+
+ let otherSandbox = Cu.Sandbox(null, {});
+ let errorFactories = [
+ msg => { throw new context.cloneScope.Error(msg); },
+ msg => context.cloneScope.Promise.reject({message: msg}),
+ msg => Cu.evalInSandbox(`throw new Error("${msg}")`, otherSandbox),
+ msg => Cu.evalInSandbox(`Promise.reject({message: "${msg}"})`, otherSandbox),
+ ];
+ for (let makeError of errorFactories) {
+ do_print(`Testing callback/promise with error caused by: ${makeError}`);
+ testnamespace = generateAPIs({
+ isChromeCompat,
+ }, {
+ async_required() { return makeError("ONE"); },
+ async_optional() { return makeError("TWO"); },
+ });
+
+ if (!isChromeCompat) { // No promises for chrome.
+ yield Assert.rejects(testnamespace.async_required(), /ONE/,
+ "should reject testnamespace.async_required()").catch(() => {});
+ yield Assert.rejects(testnamespace.async_optional(), /TWO/,
+ "should reject testnamespace.async_optional()").catch(() => {});
+ }
+
+ do_check_eq(yield* runFailCallback(testnamespace.async_required), "ONE");
+ do_check_eq(yield* runFailCallback(testnamespace.async_optional), "TWO");
+ }
+ }
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js b/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js
new file mode 100644
index 000000000..91b10354c
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js
@@ -0,0 +1,69 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+add_task(function* test_simple() {
+ let extensionData = {
+ manifest: {
+ "name": "Simple extension test",
+ "version": "1.0",
+ "manifest_version": 2,
+ "description": "",
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.unload();
+});
+
+add_task(function* test_background() {
+ function background() {
+ browser.test.log("running background script");
+
+ browser.test.onMessage.addListener((x, y) => {
+ browser.test.assertEq(x, 10, "x is 10");
+ browser.test.assertEq(y, 20, "y is 20");
+
+ browser.test.notifyPass("background test passed");
+ });
+
+ browser.test.sendMessage("running", 1);
+ }
+
+ let extensionData = {
+ background,
+ manifest: {
+ "name": "Simple extension test",
+ "version": "1.0",
+ "manifest_version": 2,
+ "description": "",
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]);
+ equal(x, 1, "got correct value from extension");
+
+ extension.sendMessage(10, 20);
+ yield extension.awaitFinish();
+ yield extension.unload();
+});
+
+add_task(function* test_extensionTypes() {
+ let extensionData = {
+ background: function() {
+ browser.test.assertEq(typeof browser.extensionTypes, "object", "browser.extensionTypes exists");
+ browser.test.assertEq(typeof browser.extensionTypes.RunAt, "object", "browser.extensionTypes.RunAt exists");
+ browser.test.notifyPass("extentionTypes test passed");
+ },
+ };
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+
+ yield extension.startup();
+ yield extension.awaitFinish();
+ yield extension.unload();
+});
+
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js
new file mode 100644
index 000000000..df46dfb63
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js
@@ -0,0 +1,334 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+const STORAGE_SYNC_PREF = "webextensions.storage.sync.enabled";
+Cu.import("resource://gre/modules/Preferences.jsm");
+
+/**
+ * Utility function to ensure that all supported APIs for getting are
+ * tested.
+ *
+ * @param {string} areaName
+ * either "local" or "sync" according to what we want to test
+ * @param {string} prop
+ * "key" to look up using the storage API
+ * @param {Object} value
+ * "value" to compare against
+ */
+async function checkGetImpl(areaName, prop, value) {
+ let storage = browser.storage[areaName];
+
+ let data = await storage.get(null);
+ browser.test.assertEq(value, data[prop], `null getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get(prop);
+ browser.test.assertEq(value, data[prop], `string getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get([prop]);
+ browser.test.assertEq(value, data[prop], `array getter worked for ${prop} in ${areaName}`);
+
+ data = await storage.get({[prop]: undefined});
+ browser.test.assertEq(value, data[prop], `object getter worked for ${prop} in ${areaName}`);
+}
+
+add_task(function* test_local_cache_invalidation() {
+ function background(checkGet) {
+ browser.test.onMessage.addListener(async msg => {
+ if (msg === "set-initial") {
+ await browser.storage.local.set({"test-prop1": "value1", "test-prop2": "value2"});
+ browser.test.sendMessage("set-initial-done");
+ } else if (msg === "check") {
+ await checkGet("local", "test-prop1", "value1");
+ await checkGet("local", "test-prop2", "value2");
+ browser.test.sendMessage("check-done");
+ }
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["storage"],
+ },
+ background: `(${background})(${checkGetImpl})`,
+ });
+
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage("set-initial");
+ yield extension.awaitMessage("set-initial-done");
+
+ Services.obs.notifyObservers(null, "extension-invalidate-storage-cache", "");
+
+ extension.sendMessage("check");
+ yield extension.awaitMessage("check-done");
+
+ yield extension.unload();
+});
+
+add_task(function* test_config_flag_needed() {
+ function background() {
+ let promises = [];
+ let apiTests = [
+ {method: "get", args: ["foo"]},
+ {method: "set", args: [{foo: "bar"}]},
+ {method: "remove", args: ["foo"]},
+ {method: "clear", args: []},
+ ];
+ apiTests.forEach(testDef => {
+ promises.push(browser.test.assertRejects(
+ browser.storage.sync[testDef.method](...testDef.args),
+ "Please set webextensions.storage.sync.enabled to true in about:config",
+ `storage.sync.${testDef.method} is behind a flag`));
+ });
+
+ Promise.all(promises).then(() => browser.test.notifyPass("flag needed"));
+ }
+
+ ok(!Preferences.get(STORAGE_SYNC_PREF));
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["storage"],
+ },
+ background: `(${background})(${checkGetImpl})`,
+ });
+
+ yield extension.startup();
+ yield extension.awaitFinish("flag needed");
+ yield extension.unload();
+});
+
+add_task(function* test_reloading_extensions_works() {
+ // Just some random extension ID that we can re-use
+ const extensionId = "my-extension-id@1";
+
+ function loadExtension() {
+ function background() {
+ browser.storage.sync.set({"a": "b"}).then(() => {
+ browser.test.notifyPass("set-works");
+ });
+ }
+
+ return ExtensionTestUtils.loadExtension({
+ manifest: {
+ permissions: ["storage"],
+ },
+ background: `(${background})()`,
+ }, extensionId);
+ }
+
+ Preferences.set(STORAGE_SYNC_PREF, true);
+
+ let extension1 = loadExtension();
+
+ yield extension1.startup();
+ yield extension1.awaitFinish("set-works");
+ yield extension1.unload();
+
+ let extension2 = loadExtension();
+
+ yield extension2.startup();
+ yield extension2.awaitFinish("set-works");
+ yield extension2.unload();
+
+ Preferences.reset(STORAGE_SYNC_PREF);
+});
+
+do_register_cleanup(() => {
+ Preferences.reset(STORAGE_SYNC_PREF);
+});
+
+add_task(function* test_backgroundScript() {
+ async function backgroundScript(checkGet) {
+ let globalChanges, gResolve;
+ function clearGlobalChanges() {
+ globalChanges = new Promise(resolve => { gResolve = resolve; });
+ }
+ clearGlobalChanges();
+ let expectedAreaName;
+
+ browser.storage.onChanged.addListener((changes, areaName) => {
+ browser.test.assertEq(expectedAreaName, areaName,
+ "Expected area name received by listener");
+ gResolve(changes);
+ });
+
+ async function checkChanges(areaName, changes, message) {
+ function checkSub(obj1, obj2) {
+ for (let prop in obj1) {
+ browser.test.assertTrue(obj1[prop] !== undefined,
+ `checkChanges ${areaName} ${prop} is missing (${message})`);
+ browser.test.assertTrue(obj2[prop] !== undefined,
+ `checkChanges ${areaName} ${prop} is missing (${message})`);
+ browser.test.assertEq(obj1[prop].oldValue, obj2[prop].oldValue,
+ `checkChanges ${areaName} ${prop} old (${message})`);
+ browser.test.assertEq(obj1[prop].newValue, obj2[prop].newValue,
+ `checkChanges ${areaName} ${prop} new (${message})`);
+ }
+ }
+
+ const recentChanges = await globalChanges;
+ checkSub(changes, recentChanges);
+ checkSub(recentChanges, changes);
+ clearGlobalChanges();
+ }
+
+ /* eslint-disable dot-notation */
+ async function runTests(areaName) {
+ expectedAreaName = areaName;
+ let storage = browser.storage[areaName];
+ // Set some data and then test getters.
+ try {
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+ await checkChanges(areaName,
+ {"test-prop1": {newValue: "value1"}, "test-prop2": {newValue: "value2"}},
+ "set (a)");
+
+ await checkGet(areaName, "test-prop1", "value1");
+ await checkGet(areaName, "test-prop2", "value2");
+
+ let data = await storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"});
+ browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (a)");
+ browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (a)");
+ browser.test.assertEq("default", data["other"], "other correct");
+
+ data = await storage.get(["test-prop1", "test-prop2", "other"]);
+ browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (b)");
+ browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (b)");
+ browser.test.assertFalse("other" in data, "other correct");
+
+ // Remove data in various ways.
+ await storage.remove("test-prop1");
+ await checkChanges(areaName, {"test-prop1": {oldValue: "value1"}}, "remove string");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove string)");
+ browser.test.assertTrue("test-prop2" in data, "prop2 present (remove string)");
+
+ await storage.set({"test-prop1": "value1"});
+ await checkChanges(areaName, {"test-prop1": {newValue: "value1"}}, "set (c)");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertEq(data["test-prop1"], "value1", "prop1 correct (c)");
+ browser.test.assertEq(data["test-prop2"], "value2", "prop2 correct (c)");
+
+ await storage.remove(["test-prop1", "test-prop2"]);
+ await checkChanges(areaName,
+ {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}},
+ "remove array");
+
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove array)");
+ browser.test.assertFalse("test-prop2" in data, "prop2 absent (remove array)");
+
+ // test storage.clear
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+ // Make sure that set() handler happened before we clear the
+ // promise again.
+ await globalChanges;
+
+ clearGlobalChanges();
+ await storage.clear();
+
+ await checkChanges(areaName,
+ {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}},
+ "clear");
+ data = await storage.get(["test-prop1", "test-prop2"]);
+ browser.test.assertFalse("test-prop1" in data, "prop1 absent (clear)");
+ browser.test.assertFalse("test-prop2" in data, "prop2 absent (clear)");
+
+ // Make sure we can store complex JSON data.
+ // known previous values
+ await storage.set({"test-prop1": "value1", "test-prop2": "value2"});
+
+ // Make sure the set() handler landed.
+ await globalChanges;
+
+ clearGlobalChanges();
+ await storage.set({
+ "test-prop1": {
+ str: "hello",
+ bool: true,
+ null: null,
+ undef: undefined,
+ obj: {},
+ arr: [1, 2],
+ date: new Date(0),
+ regexp: /regexp/,
+ func: function func() {},
+ window,
+ },
+ });
+
+ await storage.set({"test-prop2": function func() {}});
+ const recentChanges = await globalChanges;
+
+ browser.test.assertEq("value1", recentChanges["test-prop1"].oldValue, "oldValue correct");
+ browser.test.assertEq("object", typeof(recentChanges["test-prop1"].newValue), "newValue is obj");
+ clearGlobalChanges();
+
+ data = await storage.get({"test-prop1": undefined, "test-prop2": undefined});
+ let obj = data["test-prop1"];
+
+ browser.test.assertEq("hello", obj.str, "string part correct");
+ browser.test.assertEq(true, obj.bool, "bool part correct");
+ browser.test.assertEq(null, obj.null, "null part correct");
+ browser.test.assertEq(undefined, obj.undef, "undefined part correct");
+ browser.test.assertEq(undefined, obj.func, "function part correct");
+ browser.test.assertEq(undefined, obj.window, "window part correct");
+ browser.test.assertEq("1970-01-01T00:00:00.000Z", obj.date, "date part correct");
+ browser.test.assertEq("/regexp/", obj.regexp, "regexp part correct");
+ browser.test.assertEq("object", typeof(obj.obj), "object part correct");
+ browser.test.assertTrue(Array.isArray(obj.arr), "array part present");
+ browser.test.assertEq(1, obj.arr[0], "arr[0] part correct");
+ browser.test.assertEq(2, obj.arr[1], "arr[1] part correct");
+ browser.test.assertEq(2, obj.arr.length, "arr.length part correct");
+
+ obj = data["test-prop2"];
+
+ browser.test.assertEq("[object Object]", {}.toString.call(obj), "function serialized as a plain object");
+ browser.test.assertEq(0, Object.keys(obj).length, "function serialized as an empty object");
+ } catch (e) {
+ browser.test.fail(`Error: ${e} :: ${e.stack}`);
+ browser.test.notifyFail("storage");
+ }
+ }
+
+ browser.test.onMessage.addListener(msg => {
+ let promise;
+ if (msg === "test-local") {
+ promise = runTests("local");
+ } else if (msg === "test-sync") {
+ promise = runTests("sync");
+ }
+ promise.then(() => browser.test.sendMessage("test-finished"));
+ });
+
+ browser.test.sendMessage("ready");
+ }
+
+ let extensionData = {
+ background: `(${backgroundScript})(${checkGetImpl})`,
+ manifest: {
+ permissions: ["storage"],
+ },
+ };
+
+ Preferences.set(STORAGE_SYNC_PREF, true);
+
+ let extension = ExtensionTestUtils.loadExtension(extensionData);
+ yield extension.startup();
+ yield extension.awaitMessage("ready");
+
+ extension.sendMessage("test-local");
+ yield extension.awaitMessage("test-finished");
+
+ extension.sendMessage("test-sync");
+ yield extension.awaitMessage("test-finished");
+
+ Preferences.reset(STORAGE_SYNC_PREF);
+ yield extension.unload();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js b/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js
new file mode 100644
index 000000000..eb3f552ed
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js
@@ -0,0 +1,85 @@
+"use strict";
+
+Cu.import("resource://gre/modules/NewTabUtils.jsm");
+
+
+function TestProvider(getLinksFn) {
+ this.getLinks = getLinksFn;
+ this._observers = new Set();
+}
+
+TestProvider.prototype = {
+ addObserver: function(observer) {
+ this._observers.add(observer);
+ },
+ notifyLinkChanged: function(link, index = -1, deleted = false) {
+ this._notifyObservers("onLinkChanged", link, index, deleted);
+ },
+ notifyManyLinksChanged: function() {
+ this._notifyObservers("onManyLinksChanged");
+ },
+ _notifyObservers: function(observerMethodName, ...args) {
+ args.unshift(this);
+ for (let obs of this._observers) {
+ if (obs[observerMethodName]) {
+ obs[observerMethodName].apply(NewTabUtils.links, args);
+ }
+ }
+ },
+};
+
+function makeLinks(links) {
+ // Important: To avoid test failures due to clock jitter on Windows XP, call
+ // Date.now() once here, not each time through the loop.
+ let frecency = 0;
+ let now = Date.now() * 1000;
+ let places = [];
+ links.map((link, i) => {
+ places.push({
+ url: link.url,
+ title: link.title,
+ lastVisitDate: now - i,
+ frecency: frecency++,
+ });
+ });
+ return places;
+}
+
+add_task(function* test_topSites() {
+ let expect = [{url: "http://example.com/", title: "site#-1"},
+ {url: "http://example0.com/", title: "site#0"},
+ {url: "http://example1.com/", title: "site#1"},
+ {url: "http://example2.com/", title: "site#2"},
+ {url: "http://example3.com/", title: "site#3"}];
+
+ let extension = ExtensionTestUtils.loadExtension({
+ manifest: {
+ "permissions": [
+ "topSites",
+ ],
+ },
+ background() {
+ browser.topSites.get(result => {
+ browser.test.sendMessage("done", result);
+ });
+ },
+ });
+
+
+ let expectedLinks = makeLinks(expect);
+ let provider = new TestProvider(done => done(expectedLinks));
+
+ NewTabUtils.initWithoutProviders();
+ NewTabUtils.links.addProvider(provider);
+
+ yield NewTabUtils.links.populateCache();
+
+ yield extension.startup();
+
+ let result = yield extension.awaitMessage("done");
+ Assert.deepEqual(expect, result, "got topSites");
+
+ yield extension.unload();
+
+ NewTabUtils.links.removeProvider(provider);
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js b/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js
new file mode 100644
index 000000000..68741a6cc
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js
@@ -0,0 +1,55 @@
+"use strict";
+
+Cu.import("resource://gre/modules/ExtensionManagement.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+function createWindowWithAddonId(addonId) {
+ let baseURI = Services.io.newURI("about:blank", null, null);
+ let originAttributes = {addonId};
+ let principal = Services.scriptSecurityManager
+ .createCodebasePrincipal(baseURI, originAttributes);
+ let chromeNav = Services.appShell.createWindowlessBrowser(true);
+ let interfaceRequestor = chromeNav.QueryInterface(Ci.nsIInterfaceRequestor);
+ let docShell = interfaceRequestor.getInterface(Ci.nsIDocShell);
+ docShell.createAboutBlankContentViewer(principal);
+
+ return {chromeNav, window: docShell.contentViewer.DOMDocument.defaultView};
+}
+
+add_task(function* test_eventpages() {
+ const {getAPILevelForWindow, getAddonIdForWindow} = ExtensionManagement;
+ const {NO_PRIVILEGES, FULL_PRIVILEGES} = ExtensionManagement.API_LEVELS;
+ const FAKE_ADDON_ID = "fakeAddonId";
+ const OTHER_ADDON_ID = "otherFakeAddonId";
+ const EMPTY_ADDON_ID = "";
+
+ let fakeAddonId = createWindowWithAddonId(FAKE_ADDON_ID);
+ equal(getAddonIdForWindow(fakeAddonId.window), FAKE_ADDON_ID,
+ "the window has the expected addonId");
+
+ let apiLevel = getAPILevelForWindow(fakeAddonId.window, FAKE_ADDON_ID);
+ equal(apiLevel, FULL_PRIVILEGES,
+ "apiLevel for the window with the right addonId should be FULL_PRIVILEGES");
+
+ apiLevel = getAPILevelForWindow(fakeAddonId.window, OTHER_ADDON_ID);
+ equal(apiLevel, NO_PRIVILEGES,
+ "apiLevel for the window with a different addonId should be NO_PRIVILEGES");
+
+ fakeAddonId.chromeNav.close();
+
+ // NOTE: check that window with an empty addon Id (which are window that are
+ // not Extensions pages) always get no WebExtensions APIs.
+ let emptyAddonId = createWindowWithAddonId(EMPTY_ADDON_ID);
+ equal(getAddonIdForWindow(emptyAddonId.window), EMPTY_ADDON_ID,
+ "the window has the expected addonId");
+
+ apiLevel = getAPILevelForWindow(emptyAddonId.window, EMPTY_ADDON_ID);
+ equal(apiLevel, NO_PRIVILEGES,
+ "apiLevel for empty addonId should be NO_PRIVILEGES");
+
+ apiLevel = getAPILevelForWindow(emptyAddonId.window, OTHER_ADDON_ID);
+ equal(apiLevel, NO_PRIVILEGES,
+ "apiLevel for an 'empty addonId' window should be always NO_PRIVILEGES");
+
+ emptyAddonId.chromeNav.close();
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js b/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js
new file mode 100644
index 000000000..c8b1ee92b
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js
@@ -0,0 +1,133 @@
+"use strict";
+
+const convService = Cc["@mozilla.org/streamConverters;1"]
+ .getService(Ci.nsIStreamConverterService);
+
+const UUID = "72b61ee3-aceb-476c-be1b-0822b036c9f1";
+const ADDON_ID = "test@web.extension";
+const URI = NetUtil.newURI(`moz-extension://${UUID}/file.css`);
+
+const FROM_TYPE = "application/vnd.mozilla.webext.unlocalized";
+const TO_TYPE = "text/css";
+
+
+function StringStream(string) {
+ let stream = Cc["@mozilla.org/io/string-input-stream;1"]
+ .createInstance(Ci.nsIStringInputStream);
+
+ stream.data = string;
+ return stream;
+}
+
+
+// Initialize the policy service with a stub localizer for our
+// add-on ID.
+add_task(function* init() {
+ const aps = Cc["@mozilla.org/addons/policy-service;1"]
+ .getService(Ci.nsIAddonPolicyService).wrappedJSObject;
+
+ let oldCallback = aps.setExtensionURIToAddonIdCallback(uri => {
+ if (uri.host == UUID) {
+ return ADDON_ID;
+ }
+ });
+
+ aps.setAddonLocalizeCallback(ADDON_ID, string => {
+ return string.replace(/__MSG_(.*?)__/g, "<localized-$1>");
+ });
+
+ do_register_cleanup(() => {
+ aps.setExtensionURIToAddonIdCallback(oldCallback);
+ aps.setAddonLocalizeCallback(ADDON_ID, null);
+ });
+});
+
+
+// Test that the synchronous converter works as expected with a
+// simple string.
+add_task(function* testSynchronousConvert() {
+ let stream = StringStream("Foo __MSG_xxx__ bar __MSG_yyy__ baz");
+
+ let resultStream = convService.convert(stream, FROM_TYPE, TO_TYPE, URI);
+
+ let result = NetUtil.readInputStreamToString(resultStream, resultStream.available());
+
+ equal(result, "Foo <localized-xxx> bar <localized-yyy> baz");
+});
+
+
+// Test that the asynchronous converter works as expected with input
+// split into multiple chunks, and a boundary in the middle of a
+// replacement token.
+add_task(function* testAsyncConvert() {
+ let listener;
+ let awaitResult = new Promise((resolve, reject) => {
+ listener = {
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener]),
+
+ onDataAvailable(request, context, inputStream, offset, count) {
+ this.resultParts.push(NetUtil.readInputStreamToString(inputStream, count));
+ },
+
+ onStartRequest() {
+ ok(!("resultParts" in this));
+ this.resultParts = [];
+ },
+
+ onStopRequest(request, context, statusCode) {
+ if (!Components.isSuccessCode(statusCode)) {
+ reject(new Error(statusCode));
+ }
+
+ resolve(this.resultParts.join("\n"));
+ },
+ };
+ });
+
+ let parts = ["Foo __MSG_x", "xx__ bar __MSG_yyy__ baz"];
+
+ let converter = convService.asyncConvertData(FROM_TYPE, TO_TYPE, listener, URI);
+ converter.onStartRequest(null, null);
+
+ for (let part of parts) {
+ converter.onDataAvailable(null, null, StringStream(part), 0, part.length);
+ }
+
+ converter.onStopRequest(null, null, Cr.NS_OK);
+
+
+ let result = yield awaitResult;
+ equal(result, "Foo <localized-xxx> bar <localized-yyy> baz");
+});
+
+
+// Test that attempting to initialize a converter with the URI of a
+// nonexistent WebExtension fails.
+add_task(function* testInvalidUUID() {
+ let uri = NetUtil.newURI("moz-extension://eb4f3be8-41c9-4970-aa6d-b84d1ecc02b2/file.css");
+ let stream = StringStream("Foo __MSG_xxx__ bar __MSG_yyy__ baz");
+
+ // Assert.throws raise a TypeError exception when the expected param
+ // is an arrow function. (See Bug 1237961 for rationale)
+ let expectInvalidContextException = function(e) {
+ return e.result === Cr.NS_ERROR_INVALID_ARG && /Invalid context/.test(e);
+ };
+
+ Assert.throws(() => {
+ convService.convert(stream, FROM_TYPE, TO_TYPE, uri);
+ }, expectInvalidContextException);
+
+ Assert.throws(() => {
+ let listener = {QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener])};
+
+ convService.asyncConvertData(FROM_TYPE, TO_TYPE, listener, uri);
+ }, expectInvalidContextException);
+});
+
+
+// Test that an empty stream does not throw an NS_ERROR_ILLEGAL_VALUE.
+add_task(function* testEmptyStream() {
+ let stream = StringStream("");
+ let resultStream = convService.convert(stream, FROM_TYPE, TO_TYPE, URI);
+ equal(resultStream.data, "");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_locale_data.js b/toolkit/components/webextensions/test/xpcshell/test_locale_data.js
new file mode 100644
index 000000000..c3cd44e57
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_locale_data.js
@@ -0,0 +1,130 @@
+"use strict";
+
+Cu.import("resource://gre/modules/Extension.jsm");
+
+/* globals ExtensionData */
+
+const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
+
+function* generateAddon(data) {
+ let id = uuidGenerator.generateUUID().number;
+
+ data = Object.assign({embedded: true}, data);
+ data.manifest = Object.assign({applications: {gecko: {id}}}, data.manifest);
+
+ let xpi = Extension.generateXPI(data);
+ do_register_cleanup(() => {
+ Services.obs.notifyObservers(xpi, "flush-cache-entry", null);
+ xpi.remove(false);
+ });
+
+ let fileURI = Services.io.newFileURI(xpi);
+ let jarURI = NetUtil.newURI(`jar:${fileURI.spec}!/webextension/`);
+
+ let extension = new ExtensionData(jarURI);
+ yield extension.readManifest();
+
+ return extension;
+}
+
+add_task(function* testMissingDefaultLocale() {
+ let extension = yield generateAddon({
+ "files": {
+ "_locales/en_US/messages.json": {},
+ },
+ });
+
+ equal(extension.errors.length, 0, "No errors reported");
+
+ yield extension.initAllLocales();
+
+ equal(extension.errors.length, 1, "One error reported");
+
+ do_print(`Got error: ${extension.errors[0]}`);
+
+ ok(extension.errors[0].includes('"default_locale" property is required'),
+ "Got missing default_locale error");
+});
+
+
+add_task(function* testInvalidDefaultLocale() {
+ let extension = yield generateAddon({
+ "manifest": {
+ "default_locale": "en",
+ },
+
+ "files": {
+ "_locales/en_US/messages.json": {},
+ },
+ });
+
+ equal(extension.errors.length, 1, "One error reported");
+
+ do_print(`Got error: ${extension.errors[0]}`);
+
+ ok(extension.errors[0].includes("Loading locale file _locales/en/messages.json"),
+ "Got invalid default_locale error");
+
+ yield extension.initAllLocales();
+
+ equal(extension.errors.length, 2, "Two errors reported");
+
+ do_print(`Got error: ${extension.errors[1]}`);
+
+ ok(extension.errors[1].includes('"default_locale" property must correspond'),
+ "Got invalid default_locale error");
+});
+
+
+add_task(function* testUnexpectedDefaultLocale() {
+ let extension = yield generateAddon({
+ "manifest": {
+ "default_locale": "en_US",
+ },
+ });
+
+ equal(extension.errors.length, 1, "One error reported");
+
+ do_print(`Got error: ${extension.errors[0]}`);
+
+ ok(extension.errors[0].includes("Loading locale file _locales/en-US/messages.json"),
+ "Got invalid default_locale error");
+
+ yield extension.initAllLocales();
+
+ equal(extension.errors.length, 2, "One error reported");
+
+ do_print(`Got error: ${extension.errors[1]}`);
+
+ ok(extension.errors[1].includes('"default_locale" property must correspond'),
+ "Got unexpected default_locale error");
+});
+
+
+add_task(function* testInvalidSyntax() {
+ let extension = yield generateAddon({
+ "manifest": {
+ "default_locale": "en_US",
+ },
+
+ "files": {
+ "_locales/en_US/messages.json": '{foo: {message: "bar", description: "baz"}}',
+ },
+ });
+
+ equal(extension.errors.length, 1, "No errors reported");
+
+ do_print(`Got error: ${extension.errors[0]}`);
+
+ ok(extension.errors[0].includes("Loading locale file _locales\/en_US\/messages\.json: SyntaxError"),
+ "Got syntax error");
+
+ yield extension.initAllLocales();
+
+ equal(extension.errors.length, 2, "One error reported");
+
+ do_print(`Got error: ${extension.errors[1]}`);
+
+ ok(extension.errors[1].includes("Loading locale file _locales\/en_US\/messages\.json: SyntaxError"),
+ "Got syntax error");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js
new file mode 100644
index 000000000..1fcb7799e
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js
@@ -0,0 +1,302 @@
+"use strict";
+
+/* global OS, HostManifestManager, NativeApp */
+Cu.import("resource://gre/modules/AppConstants.jsm");
+Cu.import("resource://gre/modules/AsyncShutdown.jsm");
+Cu.import("resource://gre/modules/ExtensionCommon.jsm");
+Cu.import("resource://gre/modules/FileUtils.jsm");
+Cu.import("resource://gre/modules/Schemas.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+const {Subprocess, SubprocessImpl} = Cu.import("resource://gre/modules/Subprocess.jsm");
+Cu.import("resource://gre/modules/NativeMessaging.jsm");
+Cu.import("resource://gre/modules/osfile.jsm");
+
+let registry = null;
+if (AppConstants.platform == "win") {
+ Cu.import("resource://testing-common/MockRegistry.jsm");
+ registry = new MockRegistry();
+ do_register_cleanup(() => {
+ registry.shutdown();
+ });
+}
+
+const REGPATH = "Software\\Mozilla\\NativeMessagingHosts";
+
+const BASE_SCHEMA = "chrome://extensions/content/schemas/manifest.json";
+
+let dir = FileUtils.getDir("TmpD", ["NativeMessaging"]);
+dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+let userDir = dir.clone();
+userDir.append("user");
+userDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+let globalDir = dir.clone();
+globalDir.append("global");
+globalDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
+
+let dirProvider = {
+ getFile(property) {
+ if (property == "XREUserNativeMessaging") {
+ return userDir.clone();
+ } else if (property == "XRESysNativeMessaging") {
+ return globalDir.clone();
+ }
+ return null;
+ },
+};
+
+Services.dirsvc.registerProvider(dirProvider);
+
+do_register_cleanup(() => {
+ Services.dirsvc.unregisterProvider(dirProvider);
+ dir.remove(true);
+});
+
+function writeManifest(path, manifest) {
+ if (typeof manifest != "string") {
+ manifest = JSON.stringify(manifest);
+ }
+ return OS.File.writeAtomic(path, manifest);
+}
+
+let PYTHON;
+add_task(function* setup() {
+ yield Schemas.load(BASE_SCHEMA);
+
+ PYTHON = yield Subprocess.pathSearch("python2.7");
+ if (PYTHON == null) {
+ PYTHON = yield Subprocess.pathSearch("python");
+ }
+ notEqual(PYTHON, null, "Found a suitable python interpreter");
+});
+
+let global = this;
+
+// Test of HostManifestManager.lookupApplication() begin here...
+let context = {
+ url: null,
+ jsonStringify(...args) { return JSON.stringify(...args); },
+ cloneScope: global,
+ logError() {},
+ preprocessors: {},
+ callOnClose: () => {},
+ forgetOnClose: () => {},
+};
+
+class MockContext extends ExtensionCommon.BaseContext {
+ constructor(extensionId) {
+ let fakeExtension = {id: extensionId};
+ super("testEnv", fakeExtension);
+ this.sandbox = Cu.Sandbox(global);
+ }
+
+ get cloneScope() {
+ return global;
+ }
+
+ get principal() {
+ return Cu.getObjectPrincipal(this.sandbox);
+ }
+}
+
+let templateManifest = {
+ name: "test",
+ description: "this is only a test",
+ path: "/bin/cat",
+ type: "stdio",
+ allowed_extensions: ["extension@tests.mozilla.org"],
+};
+
+add_task(function* test_nonexistent_manifest() {
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, "lookupApplication returns null for non-existent application");
+});
+
+const USER_TEST_JSON = OS.Path.join(userDir.path, "test.json");
+
+add_task(function* test_good_manifest() {
+ yield writeManifest(USER_TEST_JSON, templateManifest);
+ if (registry) {
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
+ `${REGPATH}\\test`, "", USER_TEST_JSON);
+ }
+
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ notEqual(result, null, "lookupApplication finds a good manifest");
+ equal(result.path, USER_TEST_JSON, "lookupApplication returns the correct path");
+ deepEqual(result.manifest, templateManifest, "lookupApplication returns the manifest contents");
+});
+
+add_task(function* test_invalid_json() {
+ yield writeManifest(USER_TEST_JSON, "this is not valid json");
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, "lookupApplication ignores bad json");
+});
+
+add_task(function* test_invalid_name() {
+ let manifest = Object.assign({}, templateManifest);
+ manifest.name = "../test";
+ yield writeManifest(USER_TEST_JSON, manifest);
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, "lookupApplication ignores an invalid name");
+});
+
+add_task(function* test_name_mismatch() {
+ let manifest = Object.assign({}, templateManifest);
+ manifest.name = "not test";
+ yield writeManifest(USER_TEST_JSON, manifest);
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ let what = (AppConstants.platform == "win") ? "registry key" : "json filename";
+ equal(result, null, `lookupApplication ignores mistmatch between ${what} and name property`);
+});
+
+add_task(function* test_missing_props() {
+ const PROPS = [
+ "name",
+ "description",
+ "path",
+ "type",
+ "allowed_extensions",
+ ];
+ for (let prop of PROPS) {
+ let manifest = Object.assign({}, templateManifest);
+ delete manifest[prop];
+
+ yield writeManifest(USER_TEST_JSON, manifest);
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, `lookupApplication ignores missing ${prop}`);
+ }
+});
+
+add_task(function* test_invalid_type() {
+ let manifest = Object.assign({}, templateManifest);
+ manifest.type = "bogus";
+ yield writeManifest(USER_TEST_JSON, manifest);
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, "lookupApplication ignores invalid type");
+});
+
+add_task(function* test_no_allowed_extensions() {
+ let manifest = Object.assign({}, templateManifest);
+ manifest.allowed_extensions = [];
+ yield writeManifest(USER_TEST_JSON, manifest);
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ equal(result, null, "lookupApplication ignores manifest with no allowed_extensions");
+});
+
+const GLOBAL_TEST_JSON = OS.Path.join(globalDir.path, "test.json");
+let globalManifest = Object.assign({}, templateManifest);
+globalManifest.description = "This manifest is from the systemwide directory";
+
+add_task(function* good_manifest_system_dir() {
+ yield OS.File.remove(USER_TEST_JSON);
+ yield writeManifest(GLOBAL_TEST_JSON, globalManifest);
+ if (registry) {
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
+ `${REGPATH}\\test`, "", null);
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
+ `${REGPATH}\\test`, "", GLOBAL_TEST_JSON);
+ }
+
+ let where = (AppConstants.platform == "win") ? "registry location" : "directory";
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ notEqual(result, null, `lookupApplication finds a manifest in the system-wide ${where}`);
+ equal(result.path, GLOBAL_TEST_JSON, `lookupApplication returns path in the system-wide ${where}`);
+ deepEqual(result.manifest, globalManifest, `lookupApplication returns manifest contents from the system-wide ${where}`);
+});
+
+add_task(function* test_user_dir_precedence() {
+ yield writeManifest(USER_TEST_JSON, templateManifest);
+ if (registry) {
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
+ `${REGPATH}\\test`, "", USER_TEST_JSON);
+ }
+ // global test.json and LOCAL_MACHINE registry key on windows are
+ // still present from the previous test
+
+ let result = yield HostManifestManager.lookupApplication("test", context);
+ notEqual(result, null, "lookupApplication finds a manifest when entries exist in both user-specific and system-wide locations");
+ equal(result.path, USER_TEST_JSON, "lookupApplication returns the user-specific path when user-specific and system-wide entries both exist");
+ deepEqual(result.manifest, templateManifest, "lookupApplication returns user-specific manifest contents with user-specific and system-wide entries both exist");
+});
+
+// Test shutdown handling in NativeApp
+add_task(function* test_native_app_shutdown() {
+ const SCRIPT = String.raw`
+import signal
+import struct
+import sys
+
+signal.signal(signal.SIGTERM, signal.SIG_IGN)
+
+while True:
+ rawlen = sys.stdin.read(4)
+ if len(rawlen) == 0:
+ signal.pause()
+ msglen = struct.unpack('@I', rawlen)[0]
+ msg = sys.stdin.read(msglen)
+
+ sys.stdout.write(struct.pack('@I', msglen))
+ sys.stdout.write(msg)
+ `;
+
+ let scriptPath = OS.Path.join(userDir.path, "wontdie.py");
+ let manifestPath = OS.Path.join(userDir.path, "wontdie.json");
+
+ const ID = "native@tests.mozilla.org";
+ let manifest = {
+ name: "wontdie",
+ description: "test async shutdown of native apps",
+ type: "stdio",
+ allowed_extensions: [ID],
+ };
+
+ if (AppConstants.platform == "win") {
+ yield OS.File.writeAtomic(scriptPath, SCRIPT);
+
+ let batPath = OS.Path.join(userDir.path, "wontdie.bat");
+ let batBody = `@ECHO OFF\n${PYTHON} -u "${scriptPath}" %*\n`;
+ yield OS.File.writeAtomic(batPath, batBody);
+ yield OS.File.setPermissions(batPath, {unixMode: 0o755});
+
+ manifest.path = batPath;
+ yield writeManifest(manifestPath, manifest);
+
+ registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
+ `${REGPATH}\\wontdie`, "", manifestPath);
+ } else {
+ yield OS.File.writeAtomic(scriptPath, `#!${PYTHON} -u\n${SCRIPT}`);
+ yield OS.File.setPermissions(scriptPath, {unixMode: 0o755});
+ manifest.path = scriptPath;
+ yield writeManifest(manifestPath, manifest);
+ }
+
+ let mockContext = new MockContext(ID);
+ let app = new NativeApp(mockContext, "wontdie");
+
+ // send a message and wait for the reply to make sure the app is running
+ let MSG = "test";
+ let recvPromise = new Promise(resolve => {
+ let listener = (what, msg) => {
+ equal(msg, MSG, "Received test message");
+ app.off("message", listener);
+ resolve();
+ };
+ app.on("message", listener);
+ });
+
+ let buffer = NativeApp.encodeMessage(mockContext, MSG);
+ app.send(buffer);
+ yield recvPromise;
+
+ app._cleanup();
+
+ do_print("waiting for async shutdown");
+ Services.prefs.setBoolPref("toolkit.asyncshutdown.testing", true);
+ AsyncShutdown.profileBeforeChange._trigger();
+ Services.prefs.clearUserPref("toolkit.asyncshutdown.testing");
+
+ let procs = yield SubprocessImpl.Process.getWorker().call("getProcesses", []);
+ equal(procs.size, 0, "native process exited");
+});
diff --git a/toolkit/components/webextensions/test/xpcshell/xpcshell.ini b/toolkit/components/webextensions/test/xpcshell/xpcshell.ini
new file mode 100644
index 000000000..d2c6fd5d0
--- /dev/null
+++ b/toolkit/components/webextensions/test/xpcshell/xpcshell.ini
@@ -0,0 +1,69 @@
+[DEFAULT]
+head = head.js
+tail =
+firefox-appdir = browser
+skip-if = appname == "thunderbird"
+support-files =
+ data/** head_sync.js
+tags = webextensions
+
+[test_csp_custom_policies.js]
+[test_csp_validator.js]
+[test_ext_alarms.js]
+[test_ext_alarms_does_not_fire.js]
+[test_ext_alarms_periodic.js]
+[test_ext_alarms_replaces.js]
+[test_ext_apimanager.js]
+[test_ext_api_permissions.js]
+[test_ext_background_generated_load_events.js]
+[test_ext_background_generated_reload.js]
+[test_ext_background_global_history.js]
+skip-if = os == "android" # Android does not use Places for history.
+[test_ext_background_private_browsing.js]
+[test_ext_background_runtime_connect_params.js]
+[test_ext_background_sub_windows.js]
+[test_ext_background_window_properties.js]
+skip-if = os == "android"
+[test_ext_contexts.js]
+[test_ext_downloads.js]
+[test_ext_downloads_download.js]
+skip-if = os == "android"
+[test_ext_downloads_misc.js]
+skip-if = os == "android"
+[test_ext_downloads_search.js]
+skip-if = os == "android"
+[test_ext_experiments.js]
+skip-if = release_or_beta
+[test_ext_extension.js]
+[test_ext_idle.js]
+[test_ext_json_parser.js]
+[test_ext_localStorage.js]
+[test_ext_management.js]
+[test_ext_management_uninstall_self.js]
+[test_ext_manifest_content_security_policy.js]
+[test_ext_manifest_incognito.js]
+[test_ext_manifest_minimum_chrome_version.js]
+[test_ext_onmessage_removelistener.js]
+[test_ext_runtime_connect_no_receiver.js]
+[test_ext_runtime_getBrowserInfo.js]
+[test_ext_runtime_getPlatformInfo.js]
+[test_ext_runtime_onInstalled_and_onStartup.js]
+[test_ext_runtime_sendMessage.js]
+[test_ext_runtime_sendMessage_errors.js]
+[test_ext_runtime_sendMessage_no_receiver.js]
+[test_ext_runtime_sendMessage_self.js]
+[test_ext_schemas.js]
+[test_ext_schemas_api_injection.js]
+[test_ext_schemas_async.js]
+[test_ext_schemas_allowed_contexts.js]
+[test_ext_simple.js]
+[test_ext_storage.js]
+[test_ext_topSites.js]
+skip-if = os == "android"
+[test_getAPILevelForWindow.js]
+[test_ext_legacy_extension_context.js]
+[test_ext_legacy_extension_embedding.js]
+[test_locale_converter.js]
+[test_locale_data.js]
+[test_native_messaging.js]
+skip-if = os == "android"