Intercepting fetch request on Flutter webview_flutter package - flutter

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

Related

How to pass data from +page.server.js to an underlying +page.svelte in Sveltekit

I have recently started learning Sveltekit and am working on a very basic project to practise. Here is the structure of the project:
|-routes/
| |-nextpage/
| └ +page.svelte
|+page.svelte
|+page.server.js
I got stuck trying to pass data from the +page.server.js to the +page.svelte located inside the nextpage/ route and I have no idea what to do.
In the main +page.svelte there is a component with a button that when pressed sends a FormData via POST request to the /results endpoint, triggering a server action called results within the +page.server.js. Then redirects to /nextpage.
Component in +page.svelte:
let myObject = {
//stuff
}
const handleSubmit = () => {
const formData = new FormData();
for(const name in myObject){
formData.append(name, myObject[name]);
}
let submit = fetch('?/results', {
method: 'POST',
body: formData
})
.finally(() => console.log("done"))
window.location = "/nextpage";
}
+page.server.js:
let myObject = {};
export const load = () => {
return {
myObject
}
}
export const actions = {
results: async({ request }) => {
const formData = await request.formData();
formData.forEach((value, key) => (myObject[key] = value));
console.log(myObject);
}
}
Now I would like to be able to show myObject in the +page.svelte in /nextpage, but the usual export let data does not work:
/nextpage +page.svelte:
<script>
export let data;
</script>
{data.myObject} //undefined`
What can I do? Thank you for your help.
OK guys, I guess all I needed was to use cookies. Since the object I was trying to pass between pages didn't need to be stored for longer than a page load, I don't think it would make sense to save it in a database. Instead, what did it in my case was to set a cookie with cookies.set('name', JSON.stringify(obj)); inside the action function in the main +page.server.js, and then get it back inside the load function of the /nextpage +page.server.js with const obj = cookies.get('name');. I'm not sure it was the cleanest way to do it, but it worked for me.
That does not work. Pages are fully separate, you cannot load data from one page into another.
If you want to share loaded data use a layout load function.
You can use +layout.js or sveltkit/stores.
sveltekit/stores are above the layout layer because they don't depend on the flow of the pages compared to the +layout.js layer which does depend.
cookies are processed locally.

How to use Steam (OpenId) to login into my Firebase powered Flutter app?

I'm building a Flutter app and I want users to be able to login through Steam (OpenId).
The app is powered by Firebase.
I'm pretty new to the whole OpenId world and I've read into it but I'm still not getting it.
I found that Firebase Supports signinWithCustomToken so I think I should get the Steam OpenId to get me one of those.
I also found two packages which might help me but I couldn't get those to work either:
https://pub.dev/packages/openid_client
https://pub.dev/packages/steam_login
If tried the following sample from the openid_client package:
_authenticate(Uri uri, String clientId, List<String> scopes) async {
try {
var issuer = await Issuer.discover(uri);
var client = Client(issuer, clientId);
print('CLAIMS:');
print(issuer.claimsMap);
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launch(url, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}
var authenticator = Authenticator(client,
scopes: scopes, port: 4000, urlLancher: urlLauncher);
var c = await authenticator.authorize();
closeWebView();
print(await c.getUserInfo());
}catch (err) {
print(err);
}
}
But I have no idea what to give as the uri, clientId and scopes.
For the uri I've tried https://steamcommunity.com/openid but when I try this I'm getting an error that it tried to Json.parse a xml response.
I've also tried the example for the steam_login package here, but that does nothing and doesn't feel like it should work within a Flutter app (even though the package states it Flutter compatible).
So if anybody could explain to me how I could achieve this with a working sample that would be great.
If I get this to work I'm planning on creating a tutorial/guide for it for others.

IONIC 3 InAppBrowser executeScript

I am using this native plugin to open a InAppBrowser. Also I want to inject a css and/or JS in that page, as in that page mentioned, I should use below code for css inject but it doesn't work:
browser.on('loadstop').subscribe(event => {
browser.insertCSS({ code: "body{color: red;" });
});
Can anyone help me?
You can execute javascript with below syntax
let promise = browser.executeScript({
code: '(function() {if(functionname) { return functionname(); }}())'
});
This will return promise
promise.then((values) => {
// process values here
});
where browser is instance of your inappbrowser for example -
const browser = this.iab.create('url', "_blank", this.options);

How to send http request using XMLHttpRequest instead of form request for Dropzone?

I want to upload files from my computer to the server using DropzoneJS. The documentation says to use a form which includes a URL to post to. However, instead of this I want to get the files in my javascript file so that I can send a XMLHttpRequest to the server and get a response from the same post. The problem is for some reason the Dropzone needs a URL (Even when I put
Dropzone.autoDiscover = false;
in my Javascript file with the URL, the error is gone but the dropzone isn't able to function). Is there a way to not put the form action url altogether? I do not want to make two different http requests. Here's the form:
<form method="post" enctype="multipart/form-data" id="my-awesome-dropzone" class="dropzone"></form>
Since ie10, it's possible to upload files using XHR2, like this:
if (new XMLHttpRequest().upload) {
var form = document.getElementById('my-awesome-dropzone');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
// Get the selected files from the input.
var files = fileSelect.files;
// Create a new FormData object.
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Done';
var data = xhr.responseText
// do something with the response
} else {
console.log('An error occurred!');
}
}
xhr.onerror = function() {
console.log('An error occurred!');
}
xhr.send(formData);
}
} else {
// browser doesn't support JS file uploading
}
Source: http://blog.teamtreehouse.com/uploading-files-ajax

Firefox SDK block content-type

I am developing an add-on for Firefox and i want to block a special kind of requests in content-type.
For example i want to block the application/x-rar content-types and show a message in console.log
You are able to intercept the requests by observing the http-on-examine-response notification event and check getResponseHeader('Content-Type') for application/x-rar.
'use strict';
const {
Ci, Cr
} = require('chrome');
const events = require('sdk/system/events');
events.on('http-on-examine-response', function(event) {
let channel = event.subject.QueryInterface(Ci.nsIHttpChannel);
let contentType = channel.getResponseHeader('Content-Type');
if(contentType === 'applicaiton/x-rar'){
event.subject.cancel(Cr.NS_BINDING_ABORTED);
console.log('Aborted Request', channel.name);
}
});
Best of luck with developing your add-on.