我有一个具有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 回答
经过另一天的谷歌搜索后,我发现这个页面是我问题的解决方案:Rendering HTML in a WebView with custom CSS我正在使用loadDataWithBaseUrl将数据传递到webview,但我在baseurl中传递为null,因为我不知道它是怎么做的 . 我宁愿将引用传递给我项目的assets目录 .