Loading javascript into a UIWebView from resources Loading javascript into a UIWebView from resources ios ios

Loading javascript into a UIWebView from resources

Here we go with a simple setup.

Create the following folder structure in your Resources folder.

Note that the blue folders are referenced ones

enter image description here

The css is just candy :) In lib.js resides your javascript code which you'd like to use.


<html>    <head>        <link rel="stylesheet" type="text/css" href="css/standard.css">        <script src="js/lib.js" type="text/javascript" />    </head>    <body>        <h2>Local Javascript</h2>        <a href="javascript:alert('Works!')">Test Javascript Alert</a>              <br/>        <br/>        <a href="javascript:alertMeWithMyCustomFunction('I am');">External js test</a>    </body></html>


function alertMeWithMyCustomFunction(text) {    alert(text+' -> in lib.js');}

Loading of the content in the webview

Note: webView is a property, view created with instance builder

- (void)viewDidLoad{       NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index"                                                          ofType:@"html"                                                     inDirectory:@"/htdocs" ];    NSString *html = [NSString stringWithContentsOfFile:htmlPath                                                encoding:NSUTF8StringEncoding                                                   error:nil];    [webView loadHTMLString:html                     baseURL:[NSURL fileURLWithPath:                             [NSString stringWithFormat:@"%@/htdocs/",                              [[NSBundle mainBundle] bundlePath]]]];}

And this should be the results:

enter image description hereenter image description here


snowman4415 mentioned that iOS 7 does not like self closing tags script tags, so if something is not working on iOS 7, you may need to close the tag with </script>

Here is another way to inject a local javascript file into the DOM of a web view. You load the contents of the JS file into a string and then use stringByEvalutatingJavaScriptFromString:

- (void)webViewDidFinishLoad:(UIWebView *)webView {    NSString *jsFile = @"jquery-1.8.2.min.js";    NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:jsFile ofType:nil];    NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];    NSString *javascriptCode = [NSString stringWithContentsOfFile:jsURL.path encoding:NSUTF8StringEncoding error:nil];    [webView stringByEvaluatingJavaScriptFromString:javascriptCode];    // ...}

This is especially useful when you don't own the *.html/xhtml files you are displaying (i.e. ePub reader. or news aggregator). It helps so that you don't have to worry about the relative paths from your xhtml file to your js file.

This is how I did using Webview and local JS. Putting some snapshots here a sample project here


// Get the path for index.html, where in which index.html has reference to the js files, since we are loading from the proper resource path, the JS files also gets picked up properly from the resource path.func loadWebView(){    if let resourceUrl = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "WebDocs2"){        let urlRequest = URLRequest.init(url: resourceUrl)        myWebView.loadRequest(urlRequest)    }}

// Load the JS from resourcesfunc jsScriptText() -> String? {    guard let jsPath = Bundle.main.path(forResource: "hello", ofType: "js", inDirectory: "WebDocs2/scripts") else {        return nil    }    do    {        let jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)        return jsScript    }catch{        print("Error")        return nil    }}// Run the java scriptfunc runJS(){    if let jsScript = jsScriptText(){        let jsContext = JSContext()        _ = jsContext?.evaluateScript(jsScript)        let helloJSCore = jsContext?.objectForKeyedSubscript("helloJSCore")        let result = helloJSCore?.call(withArguments: [])        print(result?.toString() ?? "Error")    }}