How can i block image loading from specific domain in GeckoView?
I tried searching equitant method like setLoadsImagesAutomatically
from webview in GeckoView but no luck.
I found few links like this and this.
Can we block image loading by injecting javaScript in GeckoView?
Advertisement
Answer
You can register a system WebExtension using installBuiltIn
that uses webRequest.onBeforeRequest
to block loading images from a given domain, or really any other criteria.
Example:
Create a folder under /assets/
for your extension, e.g. /assets/block-images
and add a manifest.json
and background.js
files like this:
manifest.json
{ "manifest_version": 2, "name": "block-images", "version": "1.0", "description": "Block images from mozilla.org", "browser_specific_settings": { "gecko": { "id": "block-images@example.com" } }, "permissions": [ "*://*.mozilla.org/*", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"] } }
background.js
"use strict"; function listener(details) { // blocks all images from twitter.com return {cancel: true}; } browser.webRequest.onBeforeRequest.addListener( listener, {urls: ["*://*.mozilla.org/*"], types: ["image"]}, ["blocking"] );
Then you can install the extension at startup somewhere using ensureBuiltIn
:
runtime .getWebExtensionController() .ensureBuiltIn( "resource://android/assets/block-images/", "block-images@example.com");
And after that any page that you load in GeckoView will block images to mozilla.org
as defined in the background.js
file.