Intercepting fetch request on Flutter webview_flutter package

1.1k views Asked by At

How can i intercept (listening) fetch request on webview_flutter package? Is it posible?

Nowadays, i was inspected flutter_inappwebview plugin. But this plugin is deprecated. Last commit on GitHub is 12 months ago.

Therefore i want intercept fetch request on webview_flutter, official Flutter package.

Is it posible making this flutter way or javascript way?


SOLVED #

I have found a solve.

I have created two interceptor on js side

1. Fetch API Interceptor

//FETCH INTERCEPTOR
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
  let [resource, config] = args;
  var requestedURL = resource.valueOf();
  console.log("requested url: "+requestedURL)
  if (requestedURL=="https://my-json-server.typicode.com/typicode/demo/comments"){
    var resp = new Response().statusText="Status not sent";
    document.querySelector('.status').style.backgroundColor="red";
    return resp;
  }else{
    const response = await originalFetch(resource, config);
    document.querySelector('.status').style.backgroundColor="green";

  return response;
  }
};

Basically replacing original window fetch api to our created fake fetch api. It's called Monkey Patching.

2. XMLHttpRequest Interceptor

//XHR INTERCEPTOR
((() => {
  const origOpen = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function() {
      console.log('request started!');
      this.addEventListener('load', function() {
          console.log(this.responseURL);
      });
      // origOpen.apply(this, arguments);
  };
}))();

and we can inject these js codes to webpage opened by Webview. with: https://pub.dev/documentation/webview_flutter/latest/webview_flutter/WebViewController/runJavascript.html

0

There are 0 answers