Intercepting AJAX in Flutter webview works on iOS but not Android - flutter

I am trying to intercept the ajax requests in webview using XMLHttpRequest. In iOS it is always working fine with flutter webview plugin but the same script injection code is not working on Android. Strange thing is it is not throwing any particular error even.
Some help on this will be really appreciable as this seems to be an elementary functional issue for webview.
Minimal example:
I am using the following Javascript code for intercepting Ajax request:
var open = window.XMLHttpRequest.prototype.open,
send = window.XMLHttpRequest.prototype.send,
onReadyStateChange;
function openReplacement(method, url, async, user, password) {
console.log('new data22');
var syncMode = async !== false ? 'async' : 'sync';
if (url === '/api/fakeCall') {
console.log('Preparing ' + syncMode + ' HTTP request : ' + method + ' ' + url);
}
return open.apply(this, arguments);
}
function sendReplacement(data) {
console.log('Sending HTTP request data : ', data);
if(this.onreadystatechange) {
this._onreadystatechange = this.onreadystatechange;
}
this.onreadystatechange = onReadyStateChangeReplacement;
return send.apply(this, arguments);
}
function onReadyStateChangeReplacement() {
console.log('HTTP request ready state changed : ' + this.readyState + ' ' + this.readyState + ' ' + XMLHttpRequest.DONE);
if (this.readyState === XMLHttpRequest.DONE) {
if (this.responseText !== "" && this.responseText !== null) {
if (this.responseText.indexOf('fareSessionUUID') !== -1) {
console.log('________________response____________');
var oData = JSON.stringify({'data': this.responseText});
console.log('new data');
console.log(oData);
window.flutter_inappbrowser.callHandler('myHandler', {foo: oData}).then(function(result) {
console.log(result, typeof result);
console.log(JSON.stringify(result));
})
}
}
}
if (this._onreadystatechange) {
return this._onreadystatechange.apply(this, arguments);
}
}
console.log(openReplacement.toString());
window.XMLHttpRequest.prototype.open = openReplacement;
window.XMLHttpRequest.prototype.send = sendReplacement;

Related

Skype web sdk audio service plugin not found

I am integrating Skype Web SDK audio service in my IONIC application. Everything works fine but I am not able to make a call. When I click on button to make a call following code gets call and I am getting Beep sound and then error about Pluginnotinstalled.
var conversation = application.conversationsManager.getConversation('tel:+XXXX');
conversation.selfParticipant.audio.state.when('Connected', function () {
console.log('Connected to audio call');
});
conversation.state.changed(function (newValue, reason, oldValue) {
console.log('Conversation state changed from', oldValue, 'to', newValue);
});
conversation.participants.added(function (participant) {
console.log('Participant:', participant.displayName(), 'has been added to the conversation');
});
conversation.audioService.start().then(function() {
console.log('The call has been started successfully');
}, function (error) {
console.log('An error occured starting the call', error);
});
When I run this code, I am getting error, Plugin not Installed. There's no description about what plugin they want.
An error occured starting the call
Error: PluginNotInstalled
Exception — skype-web-sdk.js:20782
(anonymous function) — skype-web-sdk.js:35814
exec2 — skype-web-sdk.js:21498
exec — skype-web-sdk.js:21478
dequeue — skype-web-sdk.js:21253
process — skype-web-sdk.js:21274
When I checked in details, The error is coming from below code of skype-web-sdk.js
function init(specs) {
tm && tm.record(Web.TelemetryEvent.PluginManager, {
action: 'init',
state: state()
});
if (state() == Media.PluginManager.State.Uninitialized) {
var id = '__mainPluginManager_' + guid().replace(/-/g, '_');
Media.log('PluginManager::init - id = ' + id);
language = (specs && specs.language) || "en-us";
isRtl = (specs && specs.rtl) || false;
var PluginObjectCtor_1 = (specs && specs.PluginObject) || Media.PluginObject;
tm = specs && specs.tm;
assert(!task || task.state() != 'pending');
task = new Task('Loading the media plugin.', {
cancel: function (reason) {
Media.log('PluginManager::init canceled ' + id);
stopLoadTimer();
reset(reason);
task.reject(reason);
}
});
tm && tm.monitor(task.promise, Web.TelemetryEvent.PluginManager, {
action: 'initPluginMgr',
state: state(),
id: id
});
state.set(Media.PluginManager.State.Initializing);
isPluginInstalled.get().then(function (installed) {
if (!installed)
throw Exception('PluginNotInstalled');
pluginObj = PluginObjectCtor_1({
id: id,
managerId: '_'
});
pluginObj.event(onPluginObjectEvent, 'async');
pluginObj.state.changed(onPluginObjectState);
Media.watch('pluginObject(' + id + ')::state', state);
Media.log('PluginManager::init - creating inner object');
try {
pluginObj.createInnerObject({
hide: true,
hookEvents: true
});
}
catch (err) {
state.set(Media.PluginManager.State.Uninitialized);
if (task.state() == 'pending')
task.reject(err);
}
}).catch(function (err) {
state.set(Media.PluginManager.State.Uninitialized);
if (task.state() == 'pending')
task.reject(err);
});
}
else {
// init has already been called and the plugin is either
// initializing or is already initialized; in either case
// we will return an existing promise
assert(task);
}
return task.promise;
}
Which browser are you using?
IE11 and Safari both need the Skype for Business Web App plugin which can ben found here: Getting started with Skype Web SDK development
Here you can find more information on how to check if the plugin is installed.

Integrating Branch.io in Ionic App

I am trying to send my app's link form my website with a token in the link like this :
branch.link({
stage: 'new user',
data: {
token: 543322
}},
function(err, link) {
console.log(err, link);
});
then when the app is installed by user after clicking on the link, i want to get this token to register the user.
I tried by reading Branch.io docs and implementing it but it's not working.
Can somebody tell me an Example to how to make it work?
Code in my app controller is like this
(():void => {
'use strict';
angular
.module('xyz')
.controller('abc', abc);
function abc (
$window
) {
let vm = this;
$window.Branch.setDebug(true);
$window.Branch.initSession().then(function (res) {
console.log(res);
alert('Response: ' + JSON.stringify(res));
}).catch(function (err) {
console.error(err);
alert('Error: ' + JSON.stringify(err));
});
$window.Branch.getFirstReferringParams().then(function (res) {
// Success Callback
alert('res'+res);
}).catch(function (err) {
// Error Callback
alert('err'+err);
});
$window.Branch.getLatestReferringParams().then(function (res) {
// Success Callback
alert(res);
}).catch(function (err) {
// Error Callback
alert(err);
});
function DeepLinkHandler (data) {
alert('Data from initSession: ' + data.data);
}
$window.DeepLinkHandler = DeepLinkHandler;
})();
Alex from Branch here: there are three steps to this process:
1. Create the link
You're doing this already with the code you provided in your question.
2. Integrate the Branch SDK into your app
The docs page covering the steps for this is here: https://dev.branch.io/getting-started/sdk-integration-guide/guide/cordova/
3. Watch for the incoming link, and route it
The docs page covering what you need for this is here: https://dev.branch.io/getting-started/deep-link-routing/advanced/cordova/
Basically, it is a function that will look something like this:
function DeepLinkHandler(data) {
console.log("received data: " + JSON.stringify(data));
for (key in data) {
if ((key != "type" && key != "source" && key != "bubbles" && key != "cancelBubble") && data[key] != null) {
console.log(key + ": " + data["key"]);
}
}
if (data["token"]) {
// load the view to register the user based on your token
} else {
// load your normal view
}
}

Issue with the submitAdapterAuthentication() method of the ChallengeHandler in MobileFirst v.6.3

We have an issue with the submitAdapterAuthentication() method of the ChallengeHandler in IBM MobileFirst v.6.3.
We assign callback functions to the properties 'onSuccess' and 'onFailure' in the options object.
We then provide the options object to submitAdapterAuthentication(invocationData, options) and execute it.
var ch = WL.Client.createChallengeHandler(securityTest);
//////////////////
function login (user, pass) {
tempUser = {username: user, password: pass};
userObj.user = user;
var auth = "Basic " + window.btoa(user + ":" + pass);
var invocationData = {
parameters: [auth, user],
adapter: "SingleStepAuthAdapter",
procedure: "submitLogin"
};
var options = {
onSuccess: iWon,
onFailure: iLost,
invocationContext: {invocationData: invocationData},
timeout: 10000
};
ch.submitAdapterAuthentication(invocationData, options);
});
function iWon(response) {
WL.Logger.debug('Login success! Response: ' + JSON.stringify(response));
//update user info, as somehow isUserAuthenticated return false without it
WL.Client.updateUserInfo(function(response) {
WL.Logger.debug('Updated User Info success! Response: ' + JSON.stringify(response));
});
}
function iLost(response) {
WL.Logger.debug('ERROR. Login failed! Response: ' + JSON.stringify(response));
}
Neither the onSuccess (iWon) or the onFailure (iLost) is called after executing submitAdapterAuthentication(invocationData, options).
How do we know if the authentication was successful?
Which options, events, callbacks or promises shall we look for and use?
We have also posted the issue here:
submitAdapterAuthentication not working
You are missing the definition of the functions
ch.isCustomResponse = function(response){...}
ch.handleChallenge = function(response){...}
Your code should look more like this
var ch = WL.Client.createChallengeHandler(securityTest);
ch.isCustomResponse = function(response) {
if (!response||!response.responseJSON||response.responseText === null) {
return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
return true;
} else {
return false;
}
};
ch.handleChallenge = function(response){
var authRequired = response.responseJSON.authRequired;
if (authRequired == true){
// handle the case when authentication is needed, i.e., show login form etc.
if (response.responseJSON.errorMessage) {
// authentication failed, show a message to the user indicating what went wrong
// call the login failed function or move it's contents here
iLost(response);
}
} else if (authRequired == false){
// no authentication is needed
ch.submitSuccess();
// call the login success function or move it's contents here
iWon(response);
}
};
//////////////////
function login (user, pass) {
tempUser = {username: user, password: pass};
userObj.user = user;
// is the first parameter expected by submitLogin the username or the
// Basic Authentication encoded string ???
var auth = "Basic " + window.btoa(user + ":" + pass);
var invocationData = {
parameters: [auth, user],
adapter: "SingleStepAuthAdapter",
procedure: "submitLogin"
};
ch.submitAdapterAuthentication(invocationData, {});
});
function iWon(response) {
WL.Logger.debug('Login success! Response: ' + JSON.stringify(response));
//update user info, as somehow isUserAuthenticated return false without it
WL.Client.updateUserInfo(function(response) {
WL.Logger.debug('Updated User Info success! Response: ' + JSON.stringify(response));
});
}
function iLost(response) {
WL.Logger.debug('ERROR. Login failed! Response: ' + JSON.stringify(response));
}
For more information on adapter-based authentication visit http://www-01.ibm.com/support/knowledgecenter/SSHS8R_6.3.0/com.ibm.worklight.dev.doc/devref/t_adapter_based_authenticator.html?lang=en
You should also check the getting started module on adapter-based authentication for hybrid applications https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-6-3/authentication-security/adapter-based-authentication/adapter-based-authentication-hybrid-applications/

Facebook Canvas: Can't redirect in javascript

I am working on this seemingly trivial problem since three days and ran completely out of ideas why my code doesn't work.
In a nutshell, when the user receives a facebook request and clicks on it, it should be process the invitation.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
if (window.location.href.indexOf('app_invite') !== -1 || window.location.href.indexOf('app_request') !== -1) {
var inviteeID = response.authResponse.userID;
processIncomingInvitation(inviteeID);
}
});
The problem occurs in the following function. Upon the successful $.post() request I am expecting a simple redirect:
$.post(url, function (result) {
window.location.replace('/True?fbapp=fbapp');
});
But the redirect is ignored and I don't understand why. I even put an alert('hello'); in there instead and I can clearly see it is hitting that bit of code. Why is the redirect ignored instead?
function processIncomingInvitation(inviteeID) {
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
while (match = search.exec(query)) {
urlParams[decode(match[1])] = decode(match[2]);
}
})();
var requestType = urlParams.app_request_type;
if (requestType === "user_to_user") {
var reqIDlist = urlParams.request_ids.split(',');
var requestID = reqIDlist[0];
FB.api(requestID, function (response) {
if (response.from !== undefined && response.from !== 'undefined') {
var inviterID = response.from.id;
var inviterName = response.from.name.split(" ")[0];
var url = '/friend/' + inviteeID + '/accept/' + inviterID + '/?fbapp=fbapp';
$.post(url, function (result) {
window.location.replace('/True?fbapp=fbapp');
});
deleteRequest(requestID);
}
});
}
}
I finally found the problem. The redirect was overridden by another redirect when you login the FB.
FB.Event.subscribe('auth.login', function (response) {
if (window.location.href.indexOf('notif_t=app_request') !== -1) {
alert('app_request: ' + window.location.href);
} else if (window.location.href.indexOf('notif_t=app_invite') !== -1) {
alert('app_invite: ' + window.location.href);
} else if (window.location.href.indexOf('fbapp') !== -1) {
alert('fbapp: ' + window.location.href);
window.location.replace('/?fbapp=fbapp');
}
});
You should redirect after the invite has been handled, which happens in FB.Event.subscribe('auth.authResponseChange', function (response) { ... } as described in the question.
Hence upon user login you should not redirect or the two redirects will collide. But you still want to redirect if its not an invite or request. Otherwise a returning user is stuck on login page.
The code above, now does exactly do that. I hope this helps.

JQuery ajax form submit works when debugging but not without

I've got a form that is loaded on to a page using ajax. The form is then submitted using the malsup jquery form plugin.
Strangely the form works when I add a firebug breakpoint line or an alert into this method, but when I remove the alert or debug, the submit code never runs.
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
});
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
alert("bind overlay called");//if I comment this out the formsubmit doesn't work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});}
I've tried with and without using $(document).ready and that doesn't make a difference.
Any ideas?
May be you need to call later part of your function after load completed,Try this
$(document).ready(function(){
function addAttachment(attachmentType, path){
var typeSplit = attachmentType.split(":");
if(path == null){
path = "";
}
var url = "/add/" + typeSplit[0] + "/" + typeSplit[1];
addOverlayDivs(); //adds div to load the form into
// load the form
var snippet = $('#overlay').load(url, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#overlay").html(msg + xhr.status + " " + xhr.statusText);
}
Dowork();//function call after load complete
});
}
function Dowork(){
var prefix = typeSplit[0];
var type = typeSplit[1];
//this alert will cause the submit form to work
var options = {
target: null, // target element(s) to be updated with server response
beforeSubmit: showRequest,
success: showResponse,
url: "/add/" + prefix + "/" + type,
type: "POST",
dataType: "json"
};
$('#overlayForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
}
});