gpt4 book ai didi

javascript - Android WebView "Cannot read property ' getAttribute' 未定义”

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:08 25 4
gpt4 key购买 nike

我正在尝试在 WebView 中运行网页。我正在加载的页面中有 javascript,它可以在我的桌面浏览器上运行,但不能在 android 模拟器中运行。在模拟器中,我收到此错误:

09-13 18:29:18.496 32087-32087/com.gamesmart.gamesmart I/chromium: [INFO:CONSOLE(91)] "Uncaught TypeError: Cannot read property 'getAttribute' of undefined", source: http://dev.gamesmart.com/mobile (91)

我在页面上运行的 JavaScript 如下所示:

<script>
window.onload = function(){
var items = document.querySelectorAll('a.item');
for(var i = 0; i < items.length; i++){
var item = items[i];
item.addEventListener('click', function(event){
event.preventDefault();
window.JSInterface.playGame(items[i].getAttribute('href'));
});
}
}
</script>

然后我运行的 Java 看起来像这样:

public class MainActivity extends AppCompatActivity {

private WebView webView;
private WebViewClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

JavaScriptInterface jsInterface = new JavaScriptInterface(this);

// Setup the WebView
webView = (WebView) findViewById(R.id.webView);

webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient());

webView.setInitialScale(1);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDomStorageEnabled(true);

webView.addJavascriptInterface(jsInterface, "JSInterface");

// Load a default URL into the webview
webView.loadUrl("http://dev.gamesmart.com/mobile");
}

}

我错过了什么吗?

最佳答案

尝试替换这个

window.JSInterface.playGame(items[i].getAttribute('href'));

有了这个

window.JSInterface.playGame(item.getAttribute('href'));

关于javascript - Android WebView "Cannot read property ' getAttribute' 未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39493830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com