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>
Related
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.
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>
As I am implementing a Webpage load in the UIWebView ,where the user has to fill the form and have to click the submit button. During submitting the request I am sending a return url to webpage along with the request.Once the request validates at the website end if return back to my return url.along with this it is sending some parameters.
It is successfully happening,but i am not getting that parameters.How can i get those parameters.
I have implemented the delegate method,but is not giving the parameters.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
Any help greatly appreciated.
I have been in the same Problem ,As iOS webview is not have as much functionality like in the android ,as in android there is JavaScriptInterface.But there is a method in iOS to execute the JS that is stringByEvaluatingJavaScriptFromString.
As you mention you are getting the parameters on the return url then your web developer have to get that parameters(i don't know how he will do ,but my developer did this and converted all the parameters in string) and to store in string parameter.then you can get that value using a JS Function.
NSURL *requestURL = [self.WebView.request URL];
NSLog(#"Reuest URl here is:%#",requestURL);
NSString *javaScript = [NSString stringWithFormat:#"function givResponse(){var x=document.getElementById('div-id').innerHTML;return x; } givResponse(); "];
NSString *jsonString = [self.webView stringByEvaluatingJavaScriptFromString:javaScript];
NSLog(#"The returned value is %#",jsonString);
/* Converting the string to JSON */
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Here the JSon String from the respose is :%#",json);
I'm building an iPhone app that is just a UIWebView of an existing mobile site that has a form-based login. When I login to the mobile site on iPhone Safari, I'm prompted to save my username/password, and it's then autofilled when I go back to the site later.
I'd like to enable the same functionality in the UIWebView, but for the life of me, I can't figure out how to do it. Any ideas?
Solution
Following Michael's basic model (see accepted answer), I was able to get this done. Here's what I did:
SETTING DATA
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {
//save form data
if(navigationType == UIWebViewNavigationTypeFormSubmitted) {
//grab the data from the page
NSString *username = [self.webView stringByEvaluatingJavaScriptFromString: #"document.myForm.username.value"];
NSString *password = [self.webView stringByEvaluatingJavaScriptFromString: #"document.myForm.password.value"];
//store values locally
[[NSUserDefaults standardUserDefaults] setObject:username forKey:#"username"];
[SFHFKeychainUtils storeUsername:username andPassword:password forServiceName:#"MyService" updateExisting:YES error:nil];
}
}
GETTING DATA
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//verify view is on the login page of the site (simplified)
NSURL *requestURL = [self.webView.request URL];
if ([requestURL.host isEqualToString:#"www.mydomain.com"]) {
//check for stored login credentials
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
if (username.length != 0 ) {
//create js strings
NSString *loadUsernameJS = [NSString stringWithFormat:#"document.myForm.username.value ='%#'", username];
NSString *password = [SFHFKeychainUtils getPasswordForUsername: username andServiceName:#"MyService" error:nil];
if (password.length == 0 ) password = #"";
NSString *loadPasswordJS = [NSString stringWithFormat:#"document.myForm.password.value ='%#'", password];
//autofill the form
[self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS];
[self.webView stringByEvaluatingJavaScriptFromString: loadPasswordJS];
}
}
}
Note that I'm using Buzz Andersen's awesome SFHFKeychainUtils package to store sensitive data to the iOs Keychain.
In order to get SFHFKeychainUtils working, you need to do a few things:
Add SFHFKeychainUtils.h and SFHFKeychainUtils.m to your project
Add the Security.framework to your project
#import <Security/Security.h> and #import "SFHFKeychainUtils.h"
From my looking I don't think there is an easy way to do it. Here is an idea of what might work though:
create your uiwebview
create a nsurlrequest
after your webview delegate page loaded function fires look in the request's http body
find the form for login (regex for common login forms?)
retrieve give the user the option to save it and then retrieve later
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;
}