简体   繁体   中英

Android WebView: Using Script Tags to Load an external javascript file from my assets folder

I have an android project that features a webview. This webview loads a static html file that is stored in my assets folder. Also in my assets folder is a 3rd party javascript library(rangy). there is some javascript in script tags in the head of my html file. That javascript references methods and objects from the rangy library. I have my html file reference the rangy through a script tag. when i try to use the functions and methods i get an error that reads:

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

Here are relevant snippets of code.

This is where i include 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>

Here's a really broad stroke of the rangy library. I'm only including the parts of hte library in this post that i feel are relevant to my question:

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

//This is all the code for rangy

});

Here's the part of my native js that references rangy. The catch block at the end prints the error to the body of the html document, because android webview don't provide this information by default:

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;
        } 
    };

I have a button in my app that will fire the jsHandler.restoreSelection() function. When i push that button, the background changes from white to yellow, but then the command catches an exception and replaces the body text with the error message that i posted up top. What is wrong with the set up of my app? What is the proper way to reference an external js file from an html file that is in my assets folder? (Note: i do have javascript turned on).

Thanks In Advanced!

After another day of googling i found this page which was the solution to my problem: Rendering HTML in a WebView with custom CSS I was using loadDataWithBaseUrl to pass data into the webview, but i was passing in the baseurl as null, because i didn't know what do with it. Im instead going to pass a reference to the assets directory of my project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM