title: Using JSInterface to execute events on the WebView - Android
body: <p>I have a <code>WebView</code> and some <code>JavaScript</code> functions that call some Java code. I have created a <code>JSInterface</code> that is attached to this <code>Webview</code>. The Java code that is executed via the <code>JSInterface</code> function ultimately makes changes to the <code>Webview</code> itself. </p>
  
  <p>Without a reference to the <code>WebView</code> itself, the function cannot update the <code>WebView</code>. It seems odd that my <code>JSInterface</code> implementation must contain a reference to the <code>WebView</code> to which it is attached! Is there a better way to do this? Some sample code to achieve this looks like so:    </p>
  
  <ol>
  <li><p><code>WebView</code>:</p>
  
  <pre><code>WebView m = findViewById(R.id.wv);
  m.getSettings().setJavaScriptEnabled(true);
  m.addJavascriptInterface(new MyJSInterface(), "Android");
  </code></pre></li>
  <li><p><code>JSInterface: 
  public class MyJSInterface {
  @JavascriptInterface
  public void doSomething() {
  //need to update the webview here.
  //first get the Webview.
  MYWebView m = MainActivity.getWebView();  //this is my question. I need the webview that the JSInterface is attached to.
  m.loadUrl("http://www.google.com");
  }
  }</code></p></li>
  </ol>
  
  <p>To be able to do this, I need to initialize the <code>JSInterface</code> like so: 
  <code>MyJSInterface myji = new MyJSInterface(webViewInstance);</code>
  and then do :<br>
  <code>webViewInstance.addJavascriptInterface(myji, "Android");</code></p>
  
  <p>My question:<br>
  1. Is this the right way to do this? Is this not circular, i.e., the JSInterface containing an object of the WebView object that calls it?<br>
  2. Are there better ways to do this?  </p>