最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Load a javascript method from Android Webview - Stack Overflow

programmeradmin1浏览0评论

I am trying to render a chart in an Android WebView using HighCharts.

What my app does should be simple : - Load the HTML page and external (but local) css and js files - Load data from the Java part of the app - Call a javascript function with the previously-loaded data as a parameter

I setup my webview by activating Javascript :

mWebView.getSettings().setJavaScriptEnabled(true);

And also by setting a WebClient to catch javascript's console messages :

mWebView.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(TAG, cm.message() + " -- From line "
                    + cm.lineNumber() + " of "
                    + cm.sourceId() );
            return true;
        }

    });

This is my HTML page :

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Chart</title>
    <script src="jquery.js"></script>
</head>

<body>
    <script src="highstock.js"></script>
    <script src="exporting.js"></script>
    <script language="javascript">
        function plot() {
            console.log("Hello !");
        }
    </script>
    <div id="container" style="height: 100%; width: 100%"></div>
</body>
</html>

I load this page from the app's assets by calling

mWebView.loadUrl("file:///android_asset/page.html");

My external CSS file seems to be read and I suppose the external JS files are also correctly loaded

I read everywhere that I can call my javascript method anytime by calling

mWebView.loadUrl("javascript:plot()");

However, I always get the error

Uncaught ReferenceError: plot is not defined -- From line 1 of null

Is there anything I might have forgotten ? Note that I load my page and call the javascript method right after the loadUrl call.

Thanks !

I am trying to render a chart in an Android WebView using HighCharts.

What my app does should be simple : - Load the HTML page and external (but local) css and js files - Load data from the Java part of the app - Call a javascript function with the previously-loaded data as a parameter

I setup my webview by activating Javascript :

mWebView.getSettings().setJavaScriptEnabled(true);

And also by setting a WebClient to catch javascript's console messages :

mWebView.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(TAG, cm.message() + " -- From line "
                    + cm.lineNumber() + " of "
                    + cm.sourceId() );
            return true;
        }

    });

This is my HTML page :

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="style.css" />
    <title>Chart</title>
    <script src="jquery.js"></script>
</head>

<body>
    <script src="highstock.js"></script>
    <script src="exporting.js"></script>
    <script language="javascript">
        function plot() {
            console.log("Hello !");
        }
    </script>
    <div id="container" style="height: 100%; width: 100%"></div>
</body>
</html>

I load this page from the app's assets by calling

mWebView.loadUrl("file:///android_asset/page.html");

My external CSS file seems to be read and I suppose the external JS files are also correctly loaded

I read everywhere that I can call my javascript method anytime by calling

mWebView.loadUrl("javascript:plot()");

However, I always get the error

Uncaught ReferenceError: plot is not defined -- From line 1 of null

Is there anything I might have forgotten ? Note that I load my page and call the javascript method right after the loadUrl call.

Thanks !

Share Improve this question asked Dec 30, 2014 at 17:41 ErGo_404ErGo_404 1,8114 gold badges18 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Ok, I'm sorry for your time loss. I was looking for an answer for hours, and then within 15 minutes of posting the question I found the solution.

The problem seemed to be the two consecutive calls to loadUrl. Maybe the page wasn't properly loaded yet while I was already calling the javascript function.

I added a load listener on the WebView like this

mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (url.equals("file:///android_asset/page.html")) {
                mWebView.loadUrl("javascript:plot();");
            }
        }
    });

so that I call the javascript method only when the page is pletely loaded. Now it works properly on every call.

Thank you again for your attention !

Try this:

<body>
    <script src="highstock.js"></script>
    <script src="exporting.js"></script>
    <script language="javascript">
        function plot() {
            console.log("Hello !");
        }

      plot(); //Note the calling of the function within the HTML file once loaded into webView
    </script>
    <div id="container" style="height: 100%; width: 100%"></div>
</body>

And remove the line:

mWebView.loadUrl("javascript:plot()");

If you want to pass data to your javascript function, hen send your data through the URL like this:

mWebView.loadUrl("file:///android_asset/page.html?data=something");

and use:

var param1var = getQueryVariable("data");
function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}

in your JavaScript like what is done here. You can also check out this example.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>