How to block iframes in Google Chrome Extension

2019-06-09 17:35发布

问题:

Google Chrome have option to disable flash and java and only run them on user click, how to create extension that will do this?

回答1:

You can implement this feature using the onBeforeRequest event of the webRequest API. Create a filter with type: ['sub_frame'], and extraInfoSpec ['blocking']. Then, return {cancel:true} in the event listener.

Minimal example:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
    // Save the data in `details` for later use
    // The data must be associated with the `tabId` and `frameId`, so that it
    //  can be used later
    if (your_method_says_block_it())
       return {cancel: true};
}, {
    urls: ['*://*/*'],
    types: ['sub_frame']
}, ['blocking']);

Manifest file:

 ...
    "permissions": ["webRequest", "webRequestBlocking", "*://*/*"]
 ...
  • The webRequest permission is needed to enable the API.
  • The webRequestBlocking permission is needed to make the request handling synchronous, to enable the function to modify (cancel) the request.
  • The *://*/* permission is needed to allow access to the host


回答2:

Just try adblock or disable the desired content under chrome://settings/content