以下是我的测试代码。我的问题是在第二个页面中我无法引用AndroidFunction2。我正在Nexus 7上测试,使用的是Android 4.4。但在使用Android 4.0的sumsang i9100上是可以的。
我做错了什么吗?还是这是Android的一个bug?
MainActivity
public class MainActivity extends Activity {
WebView mWebView1;
WebView mWebView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FrameLayout mainFrame = (FrameLayout) this.findViewById(R.id.mainFrame);
mWebView1 = new WebView(this);
mWebView1.getSettings().setJavaScriptEnabled(true);
mWebView1.getSettings().setSupportMultipleWindows(true);
mWebView1.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
mWebView1.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebView2 = new WebView(MainActivity.this);
mWebView2.getSettings().setJavaScriptEnabled(true);
mWebView2.getSettings().setSupportMultipleWindows(true);
mWebView2.setWebChromeClient(new WebChromeClient() {
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
Log.d("WebView", "Line: " + lineNumber + ", " + message);
}
});
mWebView2.addJavascriptInterface(new Object() {
@JavascriptInterface
public void hello2() {
}
}, "AndroidFunction2");
(( WebViewTransport )resultMsg.obj).setWebView(mWebView2);
resultMsg.sendToTarget();
mainFrame.addView(mWebView2);
return true;
}
});
mWebView1.addJavascriptInterface(new Object() {
@JavascriptInterface
public void hello1() {
}
}, "AndroidFunction1");
mWebView1.loadUrl("file:///sdcard/test_1.html");
mainFrame.addView(mWebView1);
}
}
这两个网页是
test_1.html:
<html>
<body>
<a href="test_2.html" target="_blank">goto test 2</a>
<div><a href="javascript:alert(typeof AndroidFunction1);"> alert(typeof AndroidFunction1);</a> </div>
<div><a href="javascript:alert(typeof window.AndroidFunction1);"> alert(typeof window.AndroidFunction1);</a> </div>
</body>
</html>
test_2.html
<html>
<body>
<div><a href="javascript:alert(AndroidFunction2);"> alert(AndroidFunction2);</a> </div>
<div><a href="javascript:alert(typeof window.AndroidFunction2);"> alert(typeof window.AndroidFunction2);</a> </div>
</body>
</html>