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

标签 javascript java android android-webview

我正在尝试在 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/

相关文章:

javascript - 在 JavaScript 中用正则表达式替换字符串

java - 线程 "main"java.util.UnknownFormatConversionException : Conversion = 'O' 中出现异常

java - 根据大写和数字拆分字符串

android - Facebook Account Kit 需要一个 appsecret_proof 参数错误

javascript - map 不输出任何东西,没有错误信息

javascript - 在 Angular 8 中单击时在 NgOninit 中触发事件

java - 套接字超时问题 : android client reading data from pc server

android - 以编程方式添加约束

java - 如何从 xml 文件中获取字符串形式的 URL?

javascript - 生成的 Javascript 不执行