Android WebView:使用脚本标记从我的资源文件夹加载外部javascript文件

时间:2012-05-14 20:33:42

标签: javascript android html android-webview external-js

我有一个以webview为特色的android项目。此webview加载存储在我的assets文件夹中的静态html文件。另外在我的资源文件夹中是第三方javascript库(rangy)。我的html文件头部的脚本标签中有一些javascript。那个javascript引用了rangy库中的方法和对象。我有我的html文件通过脚本标记引用rangy。当我尝试使用函数和方法时,我得到一个错误:

    Cannot call method '[any method from rangy library]' of 
    undefined

以下是相关的代码片段。

这是我包括rangy的地方:

<html lang="en">
<head>
    <title> </title>
    <meta charset="utf-8">
    <style type="text/css">
    </style>
    <script type="text/javascript" src="rangy.js"></script>
    <script type="text/javascript" src="rangy-serializer.js"></script>
    <script type="text/javascript">

    //...My native js

    </script>
</head>

在这里,这个笨拙的图书馆非常广泛。我在这篇文章中只包含了hte库的部分,我觉得这些部分与我的问题相关:

window['rangy'] = (function() {

//This is all the code for rangy

});

这是我的本土js引用rangy的部分。最后的catch块将错误打印到html文档的正文,因为android webview默认不提供此信息:

jsHandler.restoreSelection = function(selectionDetails) {

        try{
            window.document.body.style.background="yellow";
            window.rangy.deserializeSelection(decodeURIComponent(selectionDetails.replace(/\s+$/, "")));
            window.document.body.style.background="green";
        }
        catch(err){
            window.document.body.innerHTML = err.message;
        } 
    };

我的应用程序中有一个按钮,它将触发jsHandler.restoreSelection()函数。当我按下该按钮时,背景从白色变为黄色,但随后该命令捕获异常并将正文替换为我在顶部发布的错误消息。设置我的应用程序有什么问题?从我的资产文件夹中的html文件引用外部js文件的正确方法是什么? (注意:我确实打开了javascript)。

谢谢高级!

1 个答案:

答案 0 :(得分:4)

经过另一天的谷歌搜索后,我发现这个页面是我问题的解决方案:Rendering HTML in a WebView with custom CSS我使用loadDataWithBaseUrl将数据传递到webview,但我在baseurl中传递为null,因为我没有'我知道怎么做。我宁愿将引用传递给我项目的assets目录。