I am using webview_flutter.
I currently have a native login page in my app that takes in a user's name and password. I am trying to find a way to automatically fill in the username and password on the specific page in webview and submit the login request.
Tried doing this
webViewController.evaluateJavascript(
'''
var email = document.getElementById("CustomerEmail");
var password = document.getElementById("CustomerPassword");
email.value = "user#gmail.com";
password.value = "test123";
'''
);
but got the following errors:
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=3, WKJavaScriptExceptionMessage=TypeError: null is not an object (evaluating 'email.value = "user#gmail.com"'), WKJavaScriptExceptionColumnNumber=11, WKJavaScriptExceptionSourceURL=undefined, NSLocalizedDescription=A JavaScript exception occurred})
Greatly appreciate any help on this. Thank you.
The code works, I put it in the wrong place.
The code should be placed under onPageFinished. I had it under onWebViewCreated previously.
The following code works correctly.
WebView(
initialUrl: widget.url,
onPageFinished: (_) {
setState(() {
print("loggedin " + loggedIn.toString());
if(loggedIn == false) {
loggedIn = true;
_controller.future
.then((value) =>
value.evaluateJavascript('''
var email = document.getElementById("CustomerEmail");
var password = document.getElementById("CustomerPassword");
email.value = "user#gmail.com";
password.value = "test123";
document.getElementById('customer_login').submit();
'''));
}
});
},
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
),
Related
I am trying to connect to an graphQl api that uses the token as the password in the Basic auth section of the header. I have tried using flutter_graphql but as I only get the token back after the user logs in. I have managed to get logged in using:
String username = "";
String password = token;
String basicAuth = 'Basic' + base64Encode(utf8.encode("$username:$password"));
String projects = "query Projects{Projects{id name}}";
Uri newUri = Uri.parse("$link");
var newResponse = await http.post(newUri, headers: {
"Authorization": basicAuth,
"Content-Type": "application/graphql"
}, body: //I need to get projects here.
);
var newNonJsonData = newResponse.body;
group("Testing the graph ql data after logging in: ", () {
test("Logged in", () {
expect(newResponse.statusCode, 200);
});
test("getting the data from the api", () {
print("non json return:" + newNonJsonData);
});
});
I have tried to set the body as
jsonEncode({
'query' : prjects
})
but the moment I request the data it asks to log in.
Please could someone help!!!
I am trying to load my website content in my flutter application.
I have a link https://dev.demo.hello.example.com/id/4
I have tried using flutter_webview_plugin & webview_flutter both plugins but on both plugins i am getting below error :
WF: === Starting WebFilter logging for process Runner
WF: _userSettingsForUser mobile: {
filterBlacklist = (
);
filterWhitelist = (
);
restrictWeb = 1;
useContentFilter = 0;
useContentFilterOverrides = 0;
whitelistEnabled = 0;
}
WF: _WebFilterIsActive returning: NO
I have also tried mentioned ATS related things in info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
But still facing the same issue. I have https in my link.
Is there any work around ?
In my case, I was setting a navigationDelegate to prevent all further navigation :
WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (navigation) => navigation.url == url ? NavigationDecision.navigate : NavigationDecision.prevent,
),
It works fine on Android, the initialUrl gets loaded, and any further navigation is blocked.
But on iOS I had to change this code as it was blocking even initialUrl :
WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (navigation) => navigation.url == url ? NavigationDecision.navigate : NavigationDecision.prevent,
),
Yes, just put this code to your navigationDelegate in WebView widget
navigationDelegate: (NavigationRequest request) {
if (request.url == get.url) {
return NavigationDecision.navigate;
}
return NavigationDecision.prevent;
}
it work for me on IoS & Android
I want to write an application that makes me register from app and send post request and get response to inappwebview just like exam below
InAppWebView(
initialUrl: widget.initUrls,
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
mediaPlaybackRequiresUserGesture: false,
debuggingEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController c){
_controller = c;
if(staticEmail != null && staticPass != null) {
_controller.postUrl(url: "https://xxxxxxx.com/my-account", postData: utf8.encode(
"email=${staticEmail}&password=${staticPass}&wooc_user_phone=${staticShop}&wooc_user_name=${staticShop}&woocommerce-register-nonce=5d1b626841&_wp_http_referer=/my-account/®ister=Register") )
.whenComplete(() => {print("done")}).catchError((err){print("err : ${err}");
isloading = false;
});
}
},
);
and it login fine.
But when I go to another link or when I close app and login again it ask me to login again i just want to save cookie or session id that doesn't make me login every time
You can make use of the CookieManager of this flutter_inappwebview package to get and set cookies. This is a singleton that the plugin uses, you can access it via:
CookieManager.instance()
My Flutter application flow works like this:
User logins
1-If login successfully, server returns a token
2-Set token to local storage in webview
3-Open Webview fullscreen to a specific URL
I am using this Webview plugin. The sample code shows that it supports local storage (it has a withLocalStorage option) but does not show how to use it.
I am aware of this question1 question2
f I correctly set the local storage, the Webview would show account page; otherwise a login page (
That's Not What Happened)
Instade am getting this error
I/chromium(13409): [INFO:CONSOLE(1)] "Uncaught SyntaxError: Invalid or unexpected token", source: (1)
My code:
void webwiew(token) {
flutterWebViewPlugin
.launch(
"URLExpml",
withLocalStorage: true,
withJavascript: true,
)
.whenComplete(() {
final res = flutterWebViewPlugin.evalJavascript("(function() { try { window.localStorage.setItem('token', $token); } catch (err) { return err; } })();");
print("Eval result webview : ${res.toString()}");
});
}
From https://github.com/fluttercommunity/flutter_webview_plugin/pull/51#issuecomment-399468804
You can wait until the first page loading is completed and then accessing LocalStorage with evalJavascript
To achieve this you can use onStateChanged.listen and check state.type == WebViewState.finishLoad
StreamSubscription<WebViewStateChanged> _onStateChanged;
_onStateChanged = flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged state) {
if (mounted) {
if (state.type == WebViewState.finishLoad) {
flutterWebviewPlugin.evalJavascript(
"window.localStorage.setItem('LOCAL_STORAGE','SOMETOKEN');" +
"document.getElementById('showLocalStorageBtn').click();"
);
}
}
});
I try to get email address of a user logged in via Facebook Module. But get error every time {"error":"An error code 2500 has occured. An active access token must be used to query information about the current user."}
My code is:
var viewClick = function() {
fb.logout();
fb.initialize();
fb.authorize();
};
var facebookLogged = function(e) {
fb.requestWithGraphPath("me?fields=name,email,first_name,last_name", {}, 'GET', function(result) {
Ti.API.info(JSON.stringify(result))
// var data = JSON.parse(e.result);
});
};
var window = Ti.UI.createWindow({exitOnClose: true, navBarHidden: true, fullscreen: true, orientationModes: [
Ti.UI.PORTRAIT,
Ti.UI.UPSIDE_PORTRAIT,
],
backgroundColor: '#f0f2f2'
});
var fb = require('facebook');
if(Ti.Platform.osname === 'android') {
window.fbProxy = fb.createActivityWorker({lifecycleContainer: window});
}
//fb.setLoginBehavior(fb.LOGIN_BEHAVIOR_NATIVE);
fb.permissions = ['email'];
window.open();
var view = Ti.UI.createView({
height: 200,
width: 200,
backgroundColor: 'red'
});
view.addEventListener('click', viewClick);
window.add(view);
fb.addEventListener('login', facebookLogged);
I also tried to provide access token code by modyfing requestWithGraphPath parameters:
fb.requestWithGraphPath("me?fields=name,email,first_name,last_name&access_token=" + e.source.accessToken, {}, 'GET', function(result) {}
but in such case I get infromation that accessToken is malformed.
TiFacebookModule: (main) [117,178060] requestWithGraphPath callback error: Malformed access token [Here is access token value]?access_token=[Here is access token value]
What I do wrong? How to get Email from FB? Any help deeply appreciated.
I had the same problem and this is what I do, for Android the requestWithGraphPath doesn't work like its IOS counterpart and the documentation is not updated either. You need to send the fields in the object and only the "me" in the first parameter:
var facebookLogged = function(e) {
fb.requestWithGraphPath("me", { fields: "name,email,first_name,last_name"}, 'GET', function(result) {
Ti.API.info(JSON.stringify(result))
// var data = JSON.parse(e.result);
});
};
Hope it helps.