Usi Usi
Usi Usi

Reputation: 2997

iPhone load Htmlstring in a UIWebView and replace text using Javascript

I have one html file like this one.

<body class="iphone" onLoad="doSomething()">
    <div id="title_wrapper"><h2 id="title">[[[TITOLO]]]</h2></div>
    <h2 id="subtitle">[[[DATA]]]</h2>
    <div id="content">
        [[[TESTO]]]
    </div>

I load it into my UIWebView and I want to replace the "[[[TESTO]]]" with the content of one NSString Variable. How can I do?

Upvotes: 2

Views: 6942

Answers (3)

Martin Gordon
Martin Gordon

Reputation: 36389

You can use UIWebView's -stringByEvaluatingJavaScriptFromString: method to modify your HTML once it has been loaded:

NSString *title = @"New Title";
[webView stringByEvaluatingJavaScriptFromString:
  [NSString stringWithFormat:@"document.getElementById('title').innerHTML = %@", title]];

Upvotes: 7

Jeroen Coup&#233;
Jeroen Coup&#233;

Reputation: 1404

I did something like that before, but I did it in objective C.

just first build your html file

[NSString stringWithFormat:@"<body class="iphone" onLoad="doSomething()"><div id="title_wrapper"><h2 id="title">%@</h2></div><h2 id="subtitle">%@</h2><div id="content">%@</div>", titolo ,data, content];

and afterwards load it into the webview like this

[webView loadHTMLString:myHtml];

Upvotes: 1

Sherman Lo
Sherman Lo

Reputation: 2759

Why do you have to do it in javascript?

To do it in Objective-C, just go:

NSString *templateHTML = [NSString stringWithContentsOfFile:@"Filename" encoding:NSUTF8Encoding error:NULL];
NSString *finalHTML = [templateHTML stringByReplacingOccurrencesOfString:@"[[TEST0]]" withString:variable];

That will get you the HTML with your variable instead of [[TEST0]], which you can then load into your UIWebView using loadHTMLString:baseURL:.

Upvotes: 6

Related Questions