Android Webview JavaScript无法在API 18或更高版本上运行 [英] Android webview javascript not working on API 18 or higher
问题描述
我想在WebView
中显示一个带有某些DOM元素的网站.我的意思是,我想删除一个特殊的div元素或将其替换为某些东西.
为此,我做了这样的事情:
要替换某些内容,我使用此模型
I want to display a website in WebView
with manipulating some DOM element. I mean, I want to remove a special div element or replace it with something.
For this purpose I did something like this:
For replacing something I use this model
document.getElementById("demo").innerHTML = "Hello World!";
我将其应用于Android WebView
,如下所示:
I apply it for Android WebView
like this:
public class WebClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, final String url) {
view.loadUrl("javascript:document.getElementById(\"jumbotron-company\").innerHTML = \"\";");
}
}
在我的API为18的设备上可以使用,但在模拟器或API大于18的设备上不能使用
It is work on my device which API is 18 but not working on emulators or device which have API greater than 18
推荐答案
@Mattia所说的正确.如果可能,使用evaluateJavascript
.另一个优点是能够从JavaScript返回结果的值.
What @Mattia said is correct. Use evaluateJavascript
if possible. It has another advantage of being able to return the value of the result back from JavaScript.
但是,如果要使用与API无关的解决方法,请确保使用loadUrl("javascript:...")
评估的代码不会产生任何返回值.分配返回分配的值.在较新版本的WebView中,此值用作替换现有页面的新页面的内容.
But if you want an API-agnostic workaround, make sure that the code you evaluate using loadUrl("javascript:...")
just doesn't produce any return value. An assignment returns the assigned value. In newer versions of WebView this value is used as contents for a new page that replaces the existing one.
您可以通过两种方式确保所评估的表达式不会产生返回值:
You can make sure that the expression you are evaluating doesn't produce a return value in two ways:
-
在末尾附加
void(0);
语句,例如loadUrl("javascript:elt.innerHTML='Hello World!';void(0);");
在不返回值的函数中运行代码,例如loadUrl("(function(){elt.innerHTML='Hello World!';})()");
run your code inside a function that doesn't return a value, e.g. loadUrl("(function(){elt.innerHTML='Hello World!';})()");
这篇关于Android Webview JavaScript无法在API 18或更高版本上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!