Dheeraj Chahar Dheeraj Chahar - 1 year ago 61
iOS Question

I want to insert jquery and javascript into HTML programatically in iOS

Have seen this code but not able to run it properly.

- (void)viewDidLoad {
[super viewDidLoad];
_webview.delegate = self;
[_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"Samplehtml" ofType:@"html"]isDirectory:NO]]];

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

So this is what i am trying.


$("p").click(function() {



<!DOCTYPE html>

<h1>My First Heading</h1>

<p>My first paragraph.</p>


Answer Source

Change your code like this. It is working on my side

-(void)viewDidLoad {
    [super viewDidLoad];
    self.webView.delegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Samplehtml" ofType:@"html"];
    NSString *htmlContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlContent baseURL:[NSURL URLWithString:@""]];

After that inside your webViewDidFinishLoad

- (void)webViewDidFinishLoad:(UIWebView *)webView {
     NSString *jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"js"];
     NSURL *jsURL = [NSURL fileURLWithPath:jsFilePath];
     NSString *javascriptCode1 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil];
     jsFilePath = [[NSBundle mainBundle] pathForResource:@"simple2" ofType:@"js"];
     jsURL = [NSURL fileURLWithPath:jsFilePath];
     NSString *javascriptCode2 = [NSString stringWithContentsOfFile:jsFilePath encoding:NSUTF8StringEncoding error:nil];
     [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@\n%@",javascriptCode1, javascriptCode2]];

Hope this will help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download