title: Inject JavaScript before html loaded with Android WebView
body: <p>I am using Android WebView to load a simple HTML page. The HTML depends on a tiny piece of Javascript code.</p>
  
  <p>I need to inject the Javascript before html loaded. So I do it like this:</p>
  
  <pre><code>public class MainActivity extends Activity {
  
      WebView mWebView;
      Button mButton;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          mWebView = (WebView)findViewById(R.id.webview);
          mWebView.getSettings().setJavaScriptEnabled(true);
          mWebView.setWebChromeClient(new WebChromeClient(){
              @Override
              public boolean onJsAlert(WebView view, String url, String message,JsResult result) {
                  return super.onJsAlert(view, url, message, result);
              }
          });
  
  
          mButton = (Button)findViewById(R.id.button);
          mButton.setOnClickListener(new myListener());
      }
  
      class myListener implements OnClickListener{
  
          int mCount = 1;
  
          @Override
          public void onClick(View arg0) {
              System.out.println("Load test page=&gt;"+mCount+" times");
              mWebView.loadUrl("javascript:var output='This string is defined before html loaded.'");
              mWebView.loadUrl("file:///android_asset/test.html");
              mCount++;
          }
      }
  }
  </code></pre>
  
  <p>HTML code:</p>
  
  <pre><code>&lt;html&gt;
  
  &lt;head&gt;
  &lt;script&gt;
  alert(output);
  &lt;/script&gt;
  &lt;head&gt;
  
  &lt;body&gt;
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>The JS and HTML works fine when I click the button first time. But when I click the button to execute the load again, it failed.</strong></p>
  
  <p>Logs:</p>
  
  <pre><code>Load test page=&gt;1 times
  Load test page=&gt;2 times
  Uncaught ReferenceError: output is not defined at file:///android_asset/test.html:5
  Load test page=&gt;3 times
  Uncaught ReferenceError: output is not defined at file:///android_asset/test.html:5
  </code></pre>
  
  <p>Any suggestion?</p>