Get Off My Lawn Get Off My Lawn - 2 months ago 32
Android Question

Android WebView "Cannot read property 'getAttribute' of undefined"

I am trying to run a web page in a WebView. The page that I am loading has javascript in it, and it works on my desktop browser but doesn't work in the android emulator. In the emulator, I get this error:


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)


The JavaScript that I am running on the page looks like this:

<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>


Then The Java that I am running looks like this:

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");
}

}


Am I missing something?

Answer

Try replacing this

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

with this

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