I'm writing a simple game. I included HTML pages + scrits into the apk file (I put them into assets folder and then loaded into a webview)
browser.loadUrl("file:///android_asset/home.html");
The prototype was only for one player and it was working fine till I needed to add authorization (to have the ability to play with a human:). I created a page for that and did a request:
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'https://www.myhost.com/login',
data: {mail:'admin#mail.com', password: '123'},
datatype: 'html',
type: 'POST',
success:function(html){
$.mobile.hidePageLoadingMsg();
$("#message").html('SUCCESS');
},
error: function(jqXHR, textStatus, errorThrown) {
$("#message").html('FAILED');
$.mobile.hidePageLoadingMsg();
}
})
This call works fine. But... then I needed to add account info to all the game pages so the server can know who is doing what. So...I decided t create a bridge for that:
browser.addJavascriptInterface(bridge, "Bridge");
On the Java side I created a function that stores success login info in the Application class (something like a session).
#JavascriptInterface
public void storeAuthData(String callback, String user, String pass) {
WebGameApplication.setUser(user);
WebGameApplication.setPassword(pass);
webview.loadUrl("javascript:"+callback);
}
And it also works. But how can I add this params if I have POST requests? I googled a lot.
For GET requests it's possible to do it here:
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
Log.i(TAG, "shouldInterceptRequest: " + url);
return super.shouldInterceptRequest(view, url);
}
But for POST I'm stuck. Maybe the solution I picked is incorrect? Of course I can extend the bridge by adding one extra method to retrive account info and then include this into each call whether it GET or POST.... but Really? There's no way of doing that?
Thanks in advance.
I'm afraid that POST requests are not passed through shouldInterceptRequest, only GET.
Could you set a cookie with the auth data rather than (or in addition to) using a JavaScript Bridge?
FYI, you should update your storeAuthData function such that it posts a task to the WebView, something like this:
#JavascriptInterface
public void storeAuthData(String callback, String user, String pass) {
...
webview.post(new Runnable() {
#Override
public void run() {
webview.loadUrl("javascript:"+callback);
}
});
}
The reason for this is important - WebView methods must be run on your applications UI thread, and JavaScript bridge callbacks are executed on a native background thread.
Related
UPDATE: it's a confirmed bug. Please upvote it here because it doesn't really receive a lot of attention from MS.
I need to override the shouldInterceptRequest method of WebViewClient to load in-app HTML content following that guide.
Here's the repo with the reproducible code: GitHub. I took a sample code from MS Q&A as well:
// ...
.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<Microsoft.Maui.Controls.WebView, ProblemHandler2>();
});
// ...
internal class ProblemHandler2 : WebViewHandler
{
protected override Android.Webkit.WebView CreatePlatformView()
{
var wv = new Android.Webkit.WebView(Android.App.Application.Context);
wv.SetWebViewClient(new CustomWebClient());
return wv;
}
}
In the repo, I included 2 custom handlers:
ProblemHandler2 is the exact snippet by the MSFT. I realized a problem: Setting MAUI WebView's Source property no longer navigates the real Android WebView:
WebViewHandler.Mapper.AppendToMapping("MyHandler", (handler, view) =>
{
#if ANDROID
var xWv = handler.PlatformView;
// For ProblemHandler2, this is needed to actually navigate:
xWv.LoadUrl("https://www.google.com/");
#endif
});
this.wv.Source = "https://www.google.com/";
ProblemHandler1 uses the default result and adds a custom handler. This fixes the navigation problem, but, both problem have the same issue:
ShouldInterceptRequest is never called. It is never called on anything even when I manually click a link to navigate. What am I missing? I am sure the CustomWebClient is correctly created and set.
I noticed none of the other callbacks works as well, for example:
public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)
{
Debugger.Break();
Debug.WriteLine(url);
base.OnPageStarted(view, url, favicon);
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
Debugger.Break();
Debug.WriteLine(url);
base.OnPageFinished(view, url);
}
I also tried using WebViewHandler.Mapping but it also does not work:
WebViewHandler.Mapper.AppendToMapping("MyHandler", (handler, _) =>
{
#if ANDROID
handler.PlatformView.SetWebViewClient(new CustomWebClient());
#endif
});
I could be wrong but, I think this might have to do with your overridden version of the CreatePlatform method,
Can you try what the default WebViewHandler is doing:
protected override WebView CreatePlatformView()
{
var platformView = new MauiWebView(this, Context!)
{
LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent)
};
platformView.Settings.JavaScriptEnabled = true;
platformView.Settings.DomStorageEnabled = true;
platformView.Settings.SetSupportMultipleWindows(true);
return platformView;
}
Check this URL for the default handlers CreatePlatform setup :
https://github.com/dotnet/maui/blob/c6250a20d73e1992b4a02e6f3c26a1e6cbcbe988/src/Core/src/Handlers/WebView/WebViewHandler.Android.cs
Also don't use Application Context in Handlers, Handlers have their own Context property you can use.
Yes, it is the case as you said.
And I have created a new issue for this problem, you can follow it up here: https://github.com/dotnet/maui/issues/11004.
Thanks for your support and feedback for maui.
Best Regards.
For my mobile Unity app, I need a web view element and use the UniWebView plugin. As shown in the code below, I wrote a script to dynamically load a html string. In my app the containing scene will be loaded many times, based on user interaction.
In the editor and on iOS it works as expected. On Android the web view is shown for the first scene load after app start. But later reloads sometimes work and sometimes fail arbitrarily shwoing a white area only. This happens although the loading spinner works, so it just seems to be a visualization failure.
The script is attached below. I put the script on a simple panel gameobject which is only used to define the screen area.
Any idea how I can solve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class YouTubePlayer : MonoBehaviour
{
private UniWebView uniWebView;
public void Start()
{
uniWebView = GetComponent<UniWebView>();
if (uniWebView == null)
{
Debug.Log("YOUTUBE PLAYER: Adding uniwebview Component");
uniWebView = gameObject.AddComponent<UniWebView>();
}
uniWebView.OnPageStarted += (view, url) =>
{
Debug.Log("YOUTUBE PLAYER: OnPageStarted with url: " + url);
};
uniWebView.OnPageFinished += (view, statusCode, url) =>
{
Debug.Log("YOUTUBE PLAYER: OnPageFinished with status code: " + statusCode);
};
uniWebView.OnPageErrorReceived += (UniWebView webView, int errorCode, string errorMessage) =>
{
Debug.Log("YOUTUBE PLAYER: OnPageErrorReceived errCode: " + errorCode
+ "\n\terrMessage: " + errorMessage);
};
uniWebView.SetShowSpinnerWhileLoading(true);
uniWebView.ReferenceRectTransform = gameObject.GetComponent<RectTransform>();
uniWebView.LoadHTMLString(YoutubeHTMLString, "https://www.youtube.com/");
uniWebView.Show(true);
}
private static string YoutubeHTMLString =
#"<html>
<head></head>
<body style=""margin:0\"">
<iframe width = ""100%"" height=""100%""
src=""https://www.youtube.com/embed/Ccj_H__4KGQ"" frameborder=""0""
allow=""autoplay; encrypted-media"" allowfullscreen>
</iframe>
</body>
</html>";
}
I found out that you have to call Show() before LoadHTMLString() on the UniWebView component. I show the corrected last lines of the Start() method below.
...
uniWebView.SetShowSpinnerWhileLoading(true);
uniWebView.ReferenceRectTransform = gameObject.GetComponent<RectTransform>();
uniWebView.Show(true);
uniWebView.LoadHTMLString(YoutubeHTMLString, "https://www.youtube.com/");
}
I can not tell why this solution works, but I consider it a bug (either in UniWebView, Unity or Android). It may have to do with asynchronous threads in the background that produce sometimes a problematic order on Android (I used an old Nexus 5 with Android 6.0.1).
Nevertheless, I hope this helps somebody, as I had two bad days of try and error ... ;-)
I need to parse JSON content out of every page in my WebView, before it is shown to the user.
In order to do so, I need to parse the JSON element and only then I’m able to use the shouldOverrideUrlLoading method. I can’t use it before I’ve parsed the JSON object because I rely on that element as part of my implementation of that method.
I have created a variable called jsonParsed to indicate whether I have all needed information out of the JSON object.
At first, it is initialized to be false.
When I get a response from the server I know the object was parsed so I change the variable to be true in the onLoaded method, and then the code is ready to get the information and check it.
This is the wanted process:
Opening new page by the user
Entering automatically to shouldOverrideUrlLoading and then to the if statement(JSON wasn't parsed yet)
Getting the JSON response in OnResponse
Going back to shouldOverrideUrlLoading and entering the else statement (JSON is parsed)
As you can see, each process should go through both if and else statements, the if before the JSON was parsed, and the else after it was parsed.
The problem:
shouldOverrideUrlLoading is reached every step 1, but each time it goes into a different statement. The first time goes into the if (steps 2+3), and the next one goes into the else (step 4) and this process repeats itself...
I think the this line webView.loadUrl(loadingURL); doesn't call shouldOverrideUrlLoading for some reason.
Here is my code snippet:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
mProgressDialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView wView, String url){
loadingURL=url;
if (!jsonParsed){
/** JSON object is not parsed
* Some code for adding request
to requestQueue and than loading new url in onResponse method... */
}
else {
/** JSON object is parsed, starting checking process
* I need to check this URL and decide whether or not to override it*/
jsonParsed=false;
Root root = new Gson().fromJson(jsonResponse, Root.class);
for (Page page : root.query.pages.values()) {
firstParagraph=page.extract; //Parsing process, works fine
}
if (firstParagraph!=null) {
//If the webView isn't Wikipedia's article, it will be null
if (firstParagraph.contains(allowedContent)) {
//Passing URL to view
return true;
}
}
return false; //The URL leads to unallowed content
}
}
#Override
public void onPageFinished(WebView view, String url) {
CloseBlocksAndDisableEdit(view);
mProgressDialog.dismiss();
}
private final Response.Listener<String> onLoaded = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonResponse=response; //Getting response
jsonParsed=true; //Object was examined
webView.loadUrl(loadingURL);
}
};
What can be the cause of this problem?
If it's not possible in this way, I'd like to know which way is better...
I have found this answer:
https://stackoverflow.com/a/6739042/7483311
It is written in this answer:
After some research I conclude that despite what most of the tutorials
out there say, shouldOverrideUrlLoading() does not get called when:
You load a URL like:
loadUrl("http://www.google.com");
The browser redirects the user automatically via an HTTP Redirect.
This probably makes my code impposible.
In this line: webView.loadUrl(loadingURL);, I'm making an https request that was not made by the user in the WebView, and that's why it doesn't call shouldoverrideurlloading.
Is it possible for users of my Android Application to view the URLs/Post-Data of HTTP-Post Requests from this App? So they can manipulate it and also view it with their browser on a Desktop Computer?
You can use droidQuery to do this by using the beforeSend callback, and set it as a global ajax setting:
$.ajaxSetup(new AjaxOptions().beforeSend(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
AjaxOptions options = (AjaxOptions) params[0];
if (options.type().equalsIgnoreCase("post")) {
//here, show the data stored in the AjaxOptions object, such as the URL, data type, headers, etc.
}
}
}));
Calling this method in your onStart method will set it so that all HTTP POST requests made using Ajax that are set as global (default) will trigger the given function before sending the request. Inside the Function, you can view and manipulate the AjaxOptions Object.
I'm working on making a browser as a hybrid app using worklight framework for Android. I implemented my address bar as an input element which received the user input and pass the arguments to the webview to load the page.
However, I cannot figure out how to do the reverse: whenever the user click on a link in webview, I want the address bar to change to the new location.
Are you implementing a native page that is opened? If so, take a look at ChildBrowser, that basically does the same thing. It has a TextView being used as an address bar. You may decide to use it, or get the bits and pieces you want out of it. Regardless, I would image what you want to do something like this. By overriding the onLoadResource in the WebViewClient, you should be able to grab the url and change your TextBox.
In response to the comment below: inside your environment's main js file in the wlEnvInit() function:
function wlEnvInit(){
wlCommonInit();
// Environment initialization code goes here
document.onclick=manageLinks;
}
Then in this function get the url and set the text of your input element:
function manageLinks(event) {
var link = event.target;
//go up the family tree until we find the A tag
while (link && link.tagName != 'A') {
link = link.parentNode;
}
if (link) {
var url = link.href;
console.log("url = " + url);
//You can decide if you want to separate external or
//internal links, depending on your application
var linkIsExternal = ((url.indexOf('http://') == 0) || (url.indexOf('https://') == 0));
if (linkIsExternal) {
myInput.setText(url);
return false;
}
}
return true;
}
Inside of your WebView, inside the plugin, intercept the URL like this:
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//use this area to set your input. Depending on how you
//implemented your plugin, you may need to return this value
//back to your main activity
Toast.makeText(cordova.getActivity(), "Loading: " + url, Toast.LENGTH_LONG).show();
}
});
Have you try to get the url from the href of and assign to the input variable and do the get/post? I know that it is possible in SDK i figure it dont will be harder in a framework. You can store the hiperlinks in a array with a parser or something similar.
example pseudocode:
When_hiperlink_clicked: //could be like a listener (search about it)
url = hiperlink.getURL("myHiperlink");
myinput.setText(url);
execute_input_bar_action();
Is difficult to figure out without code or something more, sorry.