fix: print a deprecation warning when sendResponse callback is used for the first time

This commit is contained in:
Luca Greco 2018-05-14 18:59:13 +02:00
parent 314d2c6df7
commit 831e355650
1 changed files with 14 additions and 0 deletions

View File

@ -7,6 +7,13 @@
"use strict"; "use strict";
if (typeof browser === "undefined") { if (typeof browser === "undefined") {
const SEND_RESPONSE_DEPRECATION_WARNING = `
Returning a Promise is the preferred way to send a reply from an
onMessage/onMessageExternal listener, as the sendResponse will be
removed from the specs (See
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage)
`.replace(/\s+/g, " ").trim();
// Wrapping the bulk of this polyfill in a one-time-use function is a minor // Wrapping the bulk of this polyfill in a one-time-use function is a minor
// optimization for Firefox. Since Spidermonkey does not fully parse the // optimization for Firefox. Since Spidermonkey does not fully parse the
// contents of a function until the first time it's called, and since it will // contents of a function until the first time it's called, and since it will
@ -338,6 +345,9 @@ if (typeof browser === "undefined") {
}, },
}); });
// Keep track if the deprecation warning has been logged at least once.
let loggedSendResponseDeprecationWarning = false;
const onMessageWrappers = new DefaultWeakMap(listener => { const onMessageWrappers = new DefaultWeakMap(listener => {
if (typeof listener !== "function") { if (typeof listener !== "function") {
return listener; return listener;
@ -366,6 +376,10 @@ if (typeof browser === "undefined") {
let wrappedSendResponse; let wrappedSendResponse;
let sendResponsePromise = new Promise(resolve => { let sendResponsePromise = new Promise(resolve => {
wrappedSendResponse = function(response) { wrappedSendResponse = function(response) {
if (!loggedSendResponseDeprecationWarning) {
console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack);
loggedSendResponseDeprecationWarning = true;
}
didCallSendResponse = true; didCallSendResponse = true;
resolve(response); resolve(response);
}; };