开发者

Does JQuery really work in WebView?

Somebody say can, but I don't see any example about JQuery in WebView. I tried many ways but no succeed. This is a simple example code. The CSS works but JQuery doesn't.

1) Internet permission was added.

2) Javascript was enabled.

3) Tested on emulator 1.6 and 2.2.

public class UsingJQueryActivity extends Activity {
    private WebView webView;

    /** Called when the activity is fi开发者_StackOverflowrst created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView)findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/js_please_run.html");
    }
}

"assets/js_please_run.html"

<html>
<head>  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.js" type="text/javascript"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> 
    <script>
        alert('Hello world');
        confirm("Hello android");                       
    </script>
    <style>
    div {
        color: red;
    }
    </style>
</head>
<body>
    <div>
        All I hear is raindrops.Falling on the rooftop. Oh baby tell me why you have to go. 
        Cause this pain I feel you won't go away. And today, I'm officially missing you.
    </div>
</body>
</html>


WebView will by default not show dialogs as that is part of the UI, you'll have to test javascript in some other way or set a WebChromeClient that shows dialogs, see onJsAlert()

It is helpful to set a WebChromeClient like this one:

public class DebugWebChromeClient extends WebChromeClient {
    private static final String TAG = "DebugWebChromeClient";

    @Override
    public boolean onConsoleMessage(ConsoleMessage m) {
            Log.d(TAG, m.lineNumber() + ": " + m.message() + " - " + m.sourceId());

            return true;
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜