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>
Related
I have a UIWebView and I make it load an HTML string. The string contains http urls to images. The images get loaded, but shouldStartLoadWithRequest: method is not called for them. It is called just once, for about : blank. However all the image requests are successfully passed into my NSURLCache subclass, into cachedResponseForRequest: method. But I would like to handle the requests in the shouldStartLoadWithRequest: method. Can anything be done about that? How can I make these requests go into the delegate method?
Here is the code:
#interface URLCache : NSURLCache
#end
#implementation URLCache
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
NSLog(#"REQUEST = %#", request.URL);
return [super cachedResponseForRequest:request];
}
#end
#interface ViewController ()<UIWebViewDelegate>
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLCache setSharedURLCache:[URLCache new]];
NSString* path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"html"];
NSString* html = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:nil];
self.webView.delegate = self;
[self.webView loadHTMLString:html baseURL:nil];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"URL = %#", request.URL);
return YES;
}
#end
The shouldStartLoadWithRequest method is called only for page loads (that is, when the page as a whole gets loaded or when a frame's contents get loaded), not when loading individual resources such as images, JavaScript, or CSS.
If you want to manipulate all HTTP/HTTPS requests from a UIWebView, the only way I'm aware of to do so is by using a custom NSURLProtocol subclass. See Apple's Custom HTTP Protocol sample code project for an example of how to do this.
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.
I have two webView, in the first i load an hostname and, when webViewDidFinishLoad i take a part of current url with this method:
//Method that take a part of currentUrl of a webView
- (NSString *) webViewGetLocation {
NSString *html = [dnsWebView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
if ([html rangeOfString:#"Account"].location != NSNotFound) {
//Take loaded ip
NSString *currentURL = [dnsWebView stringByEvaluatingJavaScriptFromString:#"window.location.href"];
NSLog(#"IP TAKEN: %#", currentURL);
//Do substring to find part of ip, until the port
NSString *ip = [[self splitString: currentURL key: #"/login"] objectAtIndex: 0];
NSLog(#"IP AND PORT: %#", ip);
}
return ip;
}
and at this time all ok.
Now in the second webView, i load an url that should be composed by the ip, that i take in previous method, and a second part that not change.
My problem is: how can i take that url (return ip), since i have launched method "webViewGetLocation" in method "webViewDidFinishLoad" that do not have a return value???
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[self webViewGetLocation];
}
I try to save returned ip of method "webViewGetLocation" in an appDelegate variable, but in viewDidLoad it is empty.
Thats easy, create a class property of type NSURL in your .h file
Then set it in - (void)webViewDidFinishLoad:(UIWebView *)webView {
NSURL *url = [NSURL URLWithString:#"folder/file.html" relativeToURL:baseURL];
It's possible, in the same class, call method "webViewDidFinishLoad" more times, one for each webview for example???
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;
}
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;
}