mozilla / webextension-polyfill

A lightweight polyfill library for Promise-based WebExtension APIs in Chrome
Mozilla Public License 2.0
2.65k stars 214 forks source link

Async callback in browser.webRequest.onBeforeSendHeaders not working #225

Open JacobVarghese1992 opened 4 years ago

JacobVarghese1992 commented 4 years ago

Sorry if this part of the known limitations mentioned but I can't get this to work for the life of me. Synchronously everything works.

Editted: This is an example now straight from the MDN webdocs.

var targetPage = "https://httpbin.org/*";

/ Set UA string to Opera 12 / var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";

/ Rewrite the User-Agent header to "ua". / function rewriteUserAgentHeaderAsync(e) { var asyncRewrite = new Promise((resolve, reject) => { window.setTimeout(() => { for (var header of e.requestHeaders) { if (header.name.toLowerCase() === "user-agent") { header.value = ua; } } resolve({requestHeaders: e.requestHeaders}); }, 2000); });

return asyncRewrite; }

/* Add rewriteUserAgentHeader as a listener to onBeforeSendHeaders, only for the target page.

Make it "blocking" so we can modify the headers. */ browser.webRequest.onBeforeSendHeaders.addListener( rewriteUserAgentHeaderAsync, {urls: [targetPage]}, ["blocking", "requestHeaders"] );

manifest.json: { "name": "Getting Started Example", "version": "1.0", "description": "Build an Extension!", "permissions": ["tabs", "activeTab", "declarativeContent", "storage", "webRequest", "webRequestBlocking", "://.httpbin.org/"], "options_page": "options.html", "background": { "scripts": ["browser-polyfill.js", "background.js"], "persistent": true }, . . . . "manifest_version": 2 }

mixedpuppy commented 4 years ago

use blocking, not asyncblocking. You'll also need webRequestBlocking in the manifest permissions.

JacobVarghese1992 commented 4 years ago

@mixedpuppy : Updated to a standard exmple from MDN docs. (My old code was me experimenting which obviously didn't even Load, sorry) Like I mentioned if I have a vanilla non-promise callback it all works fine which should mean I have the basic setup right.

Rob--W commented 4 years ago

Chrome's implementation does not support promises as a return value. Return values other than objects in the "BlockingResponse" format are ignored in Chrome.

JacobVarghese1992 commented 4 years ago

@Rob--W Thanks, Yea I was naively hoping this polyfill could do some magic to get this to work in chrome. I basically need to sign a header with crypo.subtle.sign (which returns a promise) and replace the header before being sent. I'm assuming this can't be done and I can't sign it before hand.

Should this be in the list of known limitations ?

Rob--W commented 4 years ago

Good point, let's document it.

For your use case you would have to either generate the signatures for possible return values beforehand, or use a JS library that offers a synchronous interface, such as CryptoJS.