Android - load and execute javascript on external

2019-02-26 02:20发布

问题:

Lets presume I want to add a <div>hello</div> a the bottom of the webpage http://www.google.com that I loaded in a WebView. Is it possible?

I can do it for an internal webpage (a page located on the internal memory of the device).

Here is the code of my Activity:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Main extends Activity {

    private WebView mWebview;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mWebview  = new WebView(this);
        mWebview.getSettings().setJavaScriptEnabled(true);

        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }

            private final String jsFileURL = "file:///android_asset/script.js";

            @Override  
            public void onPageFinished(WebView view, String url){

                final WebView v = view;

                view.loadUrl("javascript:{" +
                        "var script = document.createElement('script');" +
                        "script.type = 'text/javascript';" +
                        "script.src = '" + jsFileURL + "';" +
                        "document.getElementsByTagName('head').item(0).appendChild(script); };");

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        v.loadUrl("javascript:job();");
                    }

                }, 100);

              }  

        });

        mWebview.loadUrl("file:///android_asset/page.html");
        //mWebview.loadUrl("http://www.google.com");

        setContentView(mWebview );

    }

}

The content of script.js located in the "/assets" folder:

function job() {
    var div = document.createElement('div');
    div.innerHTML = 'hello';
    document.getElementsByTagName('body').item(0).appendChild(div);
}

And the content of page.html located in the "/assets" folder too:

<html>
<head></head>
<body>
<div>content of my page</div>
</body>
</html>

BUT

If I change

mWebview.loadUrl("file:///android_asset/page.html");
//mWebview.loadUrl("http://www.google.com");

by

//mWebview.loadUrl("file:///android_asset/page.html");
mWebview.loadUrl("http://www.google.com");

the trick doesn't work anymore... Is there a security reason?

回答1:

Create a folder "raw" in the res : res/raw. then host yourFile.html in the folder raw. then with your code :

String link = this.getApplicationContext().getFilesDir()+ "raw/yourFile.html";

mWebview.loadUrl(link);