Android WebView“无法读取未定义的属性'getAttribute'”

时间:2016-09-14 15:03:24

标签: javascript java android android-webview

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

  

09-13 18:29:18.496 32087-32087 / com.gamesmart.gamesmart I / chromium:[INFO:CONSOLE(91)]“未捕获的TypeError:无法读取未定义的属性'getAttribute'”,来源:{{ 3}}(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");
    }

}

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

尝试替换此

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

用这个

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