1

Can i inject js file into html file? I have tried Loading javascript into a UIWebView from resources but i am unable to load js file

lib.js

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

Test.html

<!DOCTYPE html>
<html>
    <head>
        <title>MathJax</title>
        <script type=\"text/javascript\" src=\"lib.js\" />
        <script type=\"text/javascript\" src=\"MathJaxUnpacked/MathJax.js\"></script>
        <script type=\"text/x-mathjax-config\">MathJax.Hub.Config({tex2jax: {inlineMath: [[\"$\",\"$\"],[\"\\(\",\"\\)\"]]}});</script>
    </head>
    <body>
        <br>
        <a href=\"javascript:alertMeWithMyCustomFunction('I am');\">External js test</a>
        <br>
        <br>
        <a href=\"javascript:alert('Works!')\">Test Javascript Alert</a>


        <br>
            <h1>MathJax Test</h1>
        <br>
        <p>Here the HTML is dynamically inserted using loadHTMLString in a UIWebView, and the JavaScript and image are referenced from the resources of the application.</p>
        <br>
        <p>$$\\int_x^y f(x) dx$$</p>
        <br>
        <br>
        <img src=\"images/test.jpg\">
    </body>
</html>

Code in viewdidload

NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"html"];
    NSString *html = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    _webview = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
 [_webview loadHTMLString:html
                    baseURL:[NSURL fileURLWithPath:
                             [[NSBundle mainBundle] bundlePath]]];


    [self setView: _webview];

where i am doing wrong? I don't have a folder structure the file are in projects default folder structure it self. enter image description here when i click on links nothing happens

Community
  • 1
  • 1
user2798258
  • 171
  • 1
  • 4
  • 13
  • you have to call javascript function – Rushabh Apr 16 '14 at 08:59
  • I guess your js file is not loaded for some reason, because of a bad reference issue. Where is your html file located? Do both html and js files located on the same place? Did you try using Simulator with Safari's developer inspector to look for javascript errors/file loading problems? – Yaniv Efraim Apr 17 '14 at 01:09
  • both the files are in same location – user2798258 Apr 17 '14 at 06:29

1 Answers1

0

heck the UIWebView method called:

stringByEvaluatingJavaScriptFromString:(NSString *)script;

NSString *result = [_webView stringByEvaluatingJavaScriptFromString:(@"alert('test')
Rushabh
  • 3,208
  • 5
  • 28
  • 51