2

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?

3 Answers 3

7

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]];
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this solution but the text is not being replaced in the HTML content. What can be the issue or cause for this?
Make sure you have single quotes around the placeholder, e.g. ...innerHTML = '%@'
6

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

3 Comments

Wow great! I'll try it tonight and than if I have no doubt I'll mark your solution as best. Thanks so much!
And If I want to call the method doSomething() how can I do??? <body class="iphone" onLoad="doSomething()">
If you load the page in the web view, it will run doSomething() automatically on load, exactly the same as if it was run in a browser.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.