How do I edit the HTML in a UIWebView? - ios

I have a UIWebView that loads HTML. How do I access those HTML elements and change them?
I want to do something like: webView.getHTMLElement(id: main-title).value = "New title"

If you want to edit it in a form, this is how you can do it:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *evaluate = [NSString stringWithFormat:#"document.form1.main-title.value='%#';", #"New title"];
[webView stringByEvaluatingJavaScriptFromString:evaluate];
}
Or if not in a form, maybe this (untested):
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *evaluate = [NSString stringWithFormat:#"document.getElementById('main-title').value='%#';", #"New title"];
[webView stringByEvaluatingJavaScriptFromString:evaluate];
}
Note! I assume it is an editable field that you want to change. Otherwise you are talking about parsing and that concept works like this:
static BOOL firstLoad = YES;
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if (firstLoad) {
firstLoad = NO;
NSString *html = [_webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
//Edit html here, by parsing or similar.
[webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
}
}
You can read more about parsing here: Objective-C html parser

First look at this post --> Getting the HTML source code of a loaded UIWebView
Then check this one out -->
Xcode UIWebView local HTML
Hopefully this works out for you

Try this:
[webView stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"main-title\").value = \"New Title\""];
make sure you execute this code after the document is loaded.

Related

Access media library from IOS WebView

I am loading a html which contains
<input type='file'>
So whenever I click that html input to access files, I am not able to access IOS media library. I tried the following:
NSString *javaScript = #"document.getElementByID('m-addtrack')";
NSString *response = [webView stringByEvaluatingJavaScriptFromString:javaScript];
It didn't work. Any help would be appreciated.
Thanks
From Your Html View Template u need to a simple JS Stuff
Eg : A button with hyperlink
<button>Add File</button>
You can now get the click event of the "Add File" in IOS UIWebView request handler delegate method as below
- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType {
NSString *str=[request.URL absoluteString];
if ([str isEqualToString:#"app://file"]) {
// get the file data or url here
NSString *javaScript = #"jsFunction(param as url or data)";
NSString *response = [webViewstringByEvaluatingJavaScriptFromString:javaScript];
}
}
Then in your webscript
<script>
function jsFunction(data) {
//Handle
}
</script>

How to get this into code form (if statement)

How to make this statement into an actual "if statement" in Xcode?
This is what i want in the form of an "if statement" :
"if a certain link is shown in UIWebView, then image.hidden = NO;"
The UIWebView is currently showing another website, but it has a page in that website that is the certain link I mentioned in the if statement.
The code for the UIWebView is this:
.h:
IBOutlet UIWebView *Name;
NSURL *NameURL;
.m
NameURL = [NSURL URLWithString:#"mywebname.com"];
NSURLRequest *Request = [NSURLRequest requestWithURL: NameURL];
[Name loadRequest: Request];
To access the actual page content within UIWebView, you need to use
stringByEvaluatingJavaScriptFromString: to invoke some JavaScript snippet. Once the page finishes loading, the idea is to loop through all a elements and check for its href attribute, comparing it to the 'certain site' that you mentioned.
Rough implementation:
JS Code
for (var i = 0; i < document.getElementsByTagName('a').length; i++)
{
if (document.getElementsByTagName('a')[i].href.match(/google/) return 'YES';
}
return 'NO';
Obj-C Code
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *test = [webView stringByEvaluatingJavaScriptFromString:aboveJSString];
if ([test isEqualToString:#"YES"]) image.hidden = NO;
}
Hope it helps.
According to Anh Do's answer stringByEvaluatingJavaScriptFromString isn't reliable for me.
Instead you should use:
currentURL = currentWebView.request.URL.absoluteString;
So the code will be likeā€¦.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"HELLO DID GET CALLELDLLL LL LL LL ");
//get the url you webView called "Name" is displaying...
NSString *currentURL = Name.request.URL.absoluteString;
//Check if that url is "mywebname.com"
if ([currentURL isEqualToString:#"mywebname.com"])
{
image.hidden = NO;
}
}
PS. Don't for get to add delegate to you webview
By setting delegate do this..
In ViewDidLoad:
[Name setDelegate:self];
In .h file
#interface "nameofyourviewcontroller" : UIViewController<UIWebViewDelegate>

Parse RTF in Objective c

I want to parse RTF file in Objective c.Is its possible to parse it? if is possible then how can I use it into IOS.I want all the text and formatting.
I have tried in so many way to get text and formatting for this purpose I have used UIWEBVIEW but its not return any text string
NSURL *imgPath = [[NSBundle mainBundle] URLForResource:#"test" withExtension:#"rtf"];
NSData *data = [NSData dataWithContentsOfURL:imgPath];
[webView loadData:data MIMEType:#"text/rtf" textEncodingName:#"utf-8" baseURL:[NSURL URLWithString:#"/"]];
NSString *html = [webView stringByEvaluatingJavaScriptFromString: #"document.body.innerHTML"];
Here html return nil value.
Thanks
Ok, this question is very old but in case someone stumbles across this problem:
The html is nil as the webView is not finished loading. Fetch the html in the UIWebViewDelegate:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *html = [webView stringByEvaluatingJavaScriptFromString: #"document.body.innerHTML"];
NSLog(#"Html: %#",html);
}
You will get the desired html.

Setting UIDelegate for UIWebView

I read somewhere to read javascript console messages using the
- (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)message
delegate method from the UIDelegate. But how/where do I need to set the delegate of the WebView (not the UIWebView) to my custom delegate?
I know Apple doesn't allow this in the AppStore, but I just want to implement this for debugging purposes.
What I tried so far:
- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame
{
[webView setUIDelegate:[[MyCustomUIDelegate alloc] init]];
}
and
-(void) webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject
{
[webView setUIDelegate:[[MyCustomUIDelegate alloc] init]];
}
This post may help you:
How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?
You can hook UIWebView control to hidden WebKit framework and get all exceptions, executed functions and similar.
Another way is posted here: Inject javascript code into the response that invoke to a objecie-c function.
NSString* path = [[NSBundle mainBundle] pathForResource:#"script"
ofType:#"js"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
[sender stringByEvaluatingJavaScriptFromString:content];
for exapmle the javascript code may be like:
console = new Object();
console.log = function(log) {
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "ios-log:#iOS#" + log);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
console.debug = console.log;
console.info = console.log;
console.warn = console.log;
console.error = console.log;
and the objective-c code like:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
//NSLog(requestString);
NSLog(#"Request: %#", requestString);
if ([requestString hasPrefix:#"ios-log:"]) {
NSString* logString = [[requestString componentsSeparatedByString:#":#iOS#"] objectAtIndex:1];
NSLog(#"UIWebView console: %#", logString);
return NO;
}
return YES;
}

Get current URL of UIWebView

I already tried getting the current URL of my UIWebView with: webview.request.URL.
Unfortunately the NSURL was empty. Anything wrong here? I am working with Xcode 3.2.2 beta 5.
The code above should be executed in the UIWebView delegate didStartLoad.
window.location via JS didn't work reliably for me, but this did:
currentURL = currentWebView.request.URL.absoluteString;
Credit:
http://mohrt.blogspot.com/2008/10/getting-url-from-uiwebview.html
here's the code I use to grab the url every time you navigate to a different link within the webview:
- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{
self.url = aWebView.request.mainDocumentURL;
}
Matt's version is much cleaner. I recommend everyone to use that one instead of this
You could try this:
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:#"window.location"];
I too found that the approved answer above was not reliable.
But with a slight modification, it seems to work every time:
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:#"window.location.href"];
Note the addition of ".href" to the Javascript as this is hidden at the end of the line of code.
This is not correct, and will return a nil:
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:#"window.location"];
However, the code below can get a URL, but the url may not be the current URL:
NSString *url = _webView.request.URL.absoluteString;
The correct one is:
NSString *currentURL = [_webView stringByEvaluatingJavaScriptFromString:#"window.location.href"];
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSURL *currentURL = [[webView request] URL];
NSLog(#"%#",[currentURL description]);
}
Tried this for google search results on iPhone:
NSString* currentURL = webView.request.URL.absoluteString;
NSString* mainDocumentURL = webView.request.mainDocumentURL.absoluteString;
Both return the same string!
As UIWebView is deprecated, for WKWebview to get the current url is very simple.
webView.url
here the code i use :
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[[webView request] URL] absoluteString]]];
I use the shouldStartLoadWithRequest event (UIWebViewDelegate) to catch URL updates. request.mainDocumentURL.absoluteString will get you the main web page's URL (which is normally what you want), while request.URL.absoluteString will include CSS and JavaScript includes.
This always works . .
NSString* url= [webView stringByEvaluatingJavaScriptFromString:#"window.location.href"];
implement delegate method,
- (BOOL)webView:(UIWebView *)webview shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *URL = request.URL.absoluteString; NSLog(#"%#",URL);
}
URL is the what you exactly needed.
IN Swift try this,
func webViewDidFinishLoad(webView: UIWebView){
println(WebView.request?.mainDocumentURL)
}
To get current URL of the WKWebView and UIWebview
Here is the code.
if (self.wkWebView) {
NSString *URL = self.wkWebView.title;
}else if(self.uiWebView) {
NSString *URL = self.uiWebView.request.title;
}

Resources