Loading javascript into a UIWebView from resources
Asked Answered
S

5

25

I need to load javascript files from my apps resources folder. As of right now, it does read images from the resources just fine, but it's not reading javascripts for some reason.

I have been able to render html docs that reference these javascripts if the html files themselves are written into the resources, but I would like to render html/js by setting the html of a UIWebView so it can be dynamic.

Here is what I am doing:

NSString * html = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"coffee.png\"></body></html>";

NSString * path = [[NSBundle mainBundle] resourcePath]; 
path = [path stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

NSString * resourcesPath = [[NSString alloc] initWithFormat:@"file://%@/", path];
[webview loadHTMLString:html baseURL:[NSURL URLWithString:resourcesPath]];

Now, if I change the base url to my server which also has the required files, it does load correctly. It would be great to not require an internet connection. Any help is appreciated!!! ;)

I found this useful in getting images to display: iPhone Dev: UIWebView baseUrl to resources in Documents folder not App bundle

Edit:

Instead of doing the string replacing and URL encoding, I was able to get images to by simply calling resourceURL on the mainBundle, but still no javascript execution.

    NSString * setHtml = @"<!DOCTYPE html><html><head><title>MathJax</title></head><body><script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script><script type=\"text/javascript\" src=\"/MathJax/MathJax.js\"></script>$$\\int_x^y f(x) dx$$<img src=\"images/test.png\"></body></html>";
    [webview loadHTMLString:setHtml baseURL:[[NSBundle mainBundle] resourceURL]];

EDIT

If you want to help give this a shot, I have made it easier for you by creating an example project!

https://github.com/pyramation/math-test

git clone [email protected]:pyramation/math-test.git
Subauricular answered 20/4, 2011 at 16:54 Comment(1)
I was having this problem; the solution was to add the JavaScript to the Copy Bundle Resources build phase: #844320Ectopia
P
50

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.

index.html

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

lib.js

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 here enter image description here

EDIT:

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>

Poltroonery answered 27/4, 2011 at 21:38 Comment(9)
By any chance did you try the example I made? This method doesn't seem to work. I added [webview loadHTMLString:setHtml baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]]]; with no luck.Subauricular
@Nick check out DynamicHTMLWebViewController.m on the github link, I put your suggestion in there. Could you take a look?Subauricular
@Subauricular Can you create the project with the unpacked version of MathJax? It does get into the js but there is something going wrong inside.Poltroonery
@Nick, I added the unpacked version to the git repo, however I am not sure if it helped, since the local didn't even work when I switched to it. So I kept both packed and unpacked in thereSubauricular
@pyramation, I really like to help, but as long as the unpacked version doesn't work I don't think there's a chance to debug this: I've tried to get the unpacked version to work with the local test but that didn't do anything. Actually I am not familiar with MathJax.Poltroonery
I cannot upvote this answer enough. Perfect example. Thank you so much.Incus
This is an awesome answer however iOS7 as of this comment doesn't seem to like self-closing <script/> tags so I edited answer.Anhedral
@snowman4415 That is not the best edit option, rather add a hint for iOS 7, since iOS 5 and 6 is still alive.Poltroonery
Use [[NSBundle mainBundle] resourcePath] instead of [[NSBundle mainBundle] bundlePath]Pasha
N
16

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.

Nathanialnathaniel answered 20/11, 2012 at 12:44 Comment(4)
NICE !! Finally got itKane
What would be a equivalent to this in latest Swift version?Anthology
What about CSS file?Opaque
Apple Dev guide recommends to use evaluateJavaScript:completionHandler: instead - you also get a completion handler !Triumph
A
3

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

Resources

// 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 resources
func 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 script
func 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")

    }
}
Avila answered 4/3, 2017 at 13:30 Comment(0)
I
0

In swift 3.x we can use loadHTMLString(_ string: String, baseURL: URL?) function which is used for displaying script in UIWebview

 @IBOutlet weak var webView : UIWebView!
    class ViewController: UIViewController,UIWebViewDelegate {

       override func viewDidLoad() {
            super.viewDidLoad()
            webView.delegate = self
     }
     func loadWebView() {
            webView.loadHTMLString("<p>Hello, How are you doing?.</p>" , baseURL: nil)
        }
     func webViewDidFinishLoad(_ webView: UIWebView) {
            webView.frame.size.height = 1
            webView.frame.size = webView.sizeThatFits(.zero)
     }
    }

Note:- We can set height of UIWebView as i mentioned above in webViewDidFinishLoad method

Inhibit answered 21/7, 2017 at 3:12 Comment(0)
P
0

strong textWe can run custom JavaScript on a UIWebView using the method stringByEvaluatingJavaScriptFromString().This method returns the result of running the JavaScript script passed in the script parameter, or nil if the script fails.

Swift

Load script from String

webview.stringByEvaluatingJavaScriptFromString(“alert(‘This is JavaScript!’);”) 

Load script from Local file

//Suppose you have javascript file named "JavaScript.js" in project.
let filePath = NSBundle.mainBundle().pathForResource("JavaScript", ofType: "js")
        do {
let jsContent = try String.init(contentsOfFile: filePath!, encoding:
NSUTF8StringEncoding)
webview.stringByEvaluatingJavaScriptFromString(jsContent)
        }
catch let error as NSError{
            print(error.debugDescription)
}

Objective-C

Load script from String

[webview stringByEvaluatingJavaScriptFromString:@”alert(‘This is JavaScript!’);”];

Load script from Local file


//Suppose you have javascript file named "JavaScript.js" in project.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@”JavaScript” ofType:@”js”];
NSString *jsContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[webview stringByEvaluatingJavaScriptFromString:jsContent];

enter image description here

Note The stringByEvaluatingJavaScriptFromString: method waits synchronously for JavaScript evaluation to complete. If you load web content whose JavaScript code you have not vetted, invoking this method could hang your app. Best practice is to adopt the WKWebView class and use its evaluateJavaScript:completionHandler: method instead. But WKWebView is available from iOS 8.0 and later.

Propound answered 11/10, 2019 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.