I'm stuck on getting some pretty basic JS to run in my UIWebView. In the web view's delegate, I have :
- (void)webViewDidFinishLoad:(UIWebView *)wView {
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:#"document.getElementsByClassName('box')[0]"];
NSString *allHTML = [wView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
NSLog(#"someHTML: %#", someHTML);
NSLog(#"allHTML: %#", allHTML);
}
but when the method is invoked, someHTML is nil while allHTML contains the entire body of the HTML in the webview.
I've run the JS in the Safari JS console and it works just fine (it finds a div of class 'box' so I know that its in the HTML)
Any suggestions?
More info:
FWIW, result in each of the following is also nil
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString: #"document"];
NSLog (#"1. result: %#", result); //should log the document object?
result = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body"];
NSLog (#"2. result: %#", result); //should log the document body
result = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.getElementsByClassName"];
NSLog (#"3. result: %#", result); //should log a function
result = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.getElementsByClassName('box')[0]"];
NSLog (#"4. result: %#", result); //should log the node
Changing
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:#"document.getElementsByClassName('box')[0]"];
to
NSString *someHTML = [wView stringByEvaluatingJavaScriptFromString:#"document.getElementsByClassName('box')[0].innerHTML;"];
(added the .innerHTML)
makes all the difference in the world . . .
Related
I have a finished application. I can not implement the closure of VKWebView from registration at the end of registration. Since I have not encountered this in the lens - p.
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
webView.customUserAgent = "Cron";
[self.view addSubview:webView];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://myUrl"]];
[webView loadRequest:request];
in order to interact with the WKWebView, you can use the javascript functions for them.
After the WKWebView has finished loading (via delegate for example), yo can use the evaluateJavascript functions, to trigger any event in the web or in your iOS code.
For example:
[self.webview evaluateJavaScript:#"var foo = 1; foo + 1;" completionHandler:^(id result, NSError *error) {
if (error == nil)
{
if (result != nil)
{
NSInteger integerResult = [result integerValue]; // 2
NSLog(#"result: %d", integerResult);
}
}
else
{
NSLog(#"evaluateJavaScript error : %#", error.localizedDescription);
}
}];
The javascript function is:
var foo = 1; foo + 1;
There you can set any javascript function from objective-c side, or call any function in the web side.
For example, if you have a javascript function in your web site called:
func closeWeb()
You have to set the function like this:
[self.webview evaluateJavaScript:#"closeWeb();" completionHandler:^(id result, NSError *error) {
if (error == nil)
// Code for success
} else {
NSLog(#"evaluateJavaScript error : %#", error.localizedDescription);
}
}];
self.nflWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
self.nflWebView.backgroundColor = [UIColor clearColor];
self.nflWebView.opaque = NO;
[[self nflWebView] setDelegateViews: self];
self.nflWebView.tag = 10000;
[self.nflWebView loadHTMLString:html baseURL:[NSBundle mainBundle].bundleURL];
[self.view addSubview:self.nflWebView];
I have also try the another things:
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
{
NSLog(#"stringByEvaluatingJavaScriptFromString");
NSLog(#"script :%#",script);
__block NSString *resultString = nil;
__block BOOL finished = NO;
WKWebView *obj_wkwebview=[[WKWebView alloc]init];
[obj_wkwebview evaluateJavaScript:script completionHandler:^(id result, NSError *error) {
if (error == nil) {
if (result != nil) {
resultString = [NSString stringWithFormat:#"%#", result];
}
} else {
NSLog(#"evaluateJavaScript error : %#", error);
}
finished = YES;
}];
while (!finished)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return resultString;
}
its give the error.
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo=0x170c788c0 {NSLocalizedDescription=A JavaScript exception occurred}
simple html content is loading successfull but html with javascript is not loading.
I have done a lot of Googling but not success. Please Suggest me if u have any another approach to do this thing.
Thanks in advance.
I'm trying to use the following javascript library with JavasScriptCode in iOS: javascript library
I'm reading it with the following code and everything looks great!
self.jsContext = [[JSContext alloc] init];
NSURL *scriptURL = [NSURL URLWithString:#"https://cdn.rawgit.com/Ambisafe/client-javascript/master/dist/ambisafe.js"];
NSError *error = nil;
NSString *script = [NSString stringWithContentsOfURL:scriptURL encoding:NSUTF8StringEncoding error:&error];
[self.jsContext evaluateScript:script];
When I run the following code, I have the expected results:
NSString *script = [NSString stringWithFormat:#"Ambisafe.generateRandomValue"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
Results:
function (length) {
var randomBytes;
if (!length) {
length = 256 / 16;
}
randomBytes = crypto.randomBytes(Math.ceil(length));
return randomBytes.toString('hex');
}
When I try to run the indicated function, I have an "undefined" result:
NSString *script = [NSString stringWithFormat:#"Ambisafe.generateRandomValue(30)"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
I executed the following code, and I have an "undefined" result too:
NSString *script = [NSString stringWithFormat:#"crypto"];
NSString *value = [[self.jsContext evaluateScript:script] toString];
If I test the indicated javascript library on a browser, it works fine!
Please check the Fiddle link.
Any idea?
I found the origin of the problem.
The indicated library uses the "window.crypto.getRandomValues" and it doesn't work in older browsers.
https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
I am making a call to Objective C from a PhoneGap application to perform functions with Dropbox.
The problem I am having is that my callback to JavaScript is firing before a file is downloaded from Dropbox to the phone's local filesystem.
Here is my Objective C method that begins the file download from Dropbox -
- (void) restore:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* javaScript = nil;
NSLog(#"Dropbox restore method is executing");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *localPath = [documentsDirectory stringByAppendingPathComponent:#"PocketHealth-backup.bk"];
NSString *dropBoxFile = #"/PocketHealth-backup.bk";
[[self restClient] loadFile:dropBoxFile intoPath:localPath];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
javaScript = [pluginResult toSuccessCallbackString:command.callbackId];
[self writeJavascript:javaScript];
}
There is a method in Objective C that executes when the Dropbox file has been downloaded to the phone. I do get the NSLog that this method outputs after the Dropbox file download is complete. The problem is that I need to know when this event happens before I can return my JavaScript callback.
Here is the method that executes when the Dropbox file download is complete -
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
NSLog(#"File loaded into path: %#", localPath);
}
How can I wait until the Dropbox file download is complete before returning the JavaScript callback that is in the restore method?
Instead of writing the JavaScript into a local variable inside your restore method, add it as an iVar to your class, remove the call to writeJavascript: in your restore method and call writeJavascript from restClient:loadedFile:. Then it should get called when the download finished instead of when the actual download is started.
- (void) restore:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSLog(#"Dropbox restore method is executing");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSString *localPath = [documentsDirectory stringByAppendingPathComponent:#"PocketHealth-backup.bk"];
NSString *dropBoxFile = #"/PocketHealth-backup.bk";
[[self restClient] loadFile:dropBoxFile intoPath:localPath];
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
self.javaScript = [pluginResult toSuccessCallbackString:command.callbackId];
}
- (void) restClient:(DBRestClient*)client loadedFile:(NSString*)localPath
{
NSLog(#"File loaded into path: %#", localPath);
[self writeJavascript:javaScript];
}
I have the following code for my application.
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Set the values
NSString* firstValue = #"guest";
NSString* secondValue = #"guest";
// write javascript code in a string
NSString* javaScriptString = #"document.getElementById('Login1_UserName').value=%#;"
"document.getElementById('Login1_Password').value=%#;"
"document.forms['form1'].submit();";
// insert string values into javascript
javaScriptString = [NSString stringWithFormat: javaScriptString, firstValue, secondValue];
// run javascript in webview:
[webView stringByEvaluatingJavaScriptFromString: javaScriptString];
}
- (void)launchWebPageWithOptions
{
NSString *urlString = #"http://demo.leadtools.com/MedicalViewer/default.aspx";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *requestObject = [NSURLRequest requestWithURL:url];
[iOSWebView loadRequest:requestObject];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self launchWebPageWithOptions];
}
For some reason, I am unable to execute the automatic login using the javascript calls. I am no JS Expert so if you can see any error in my javaScriptString, PLEASE let me know,
First, change your user and password formatted values to be quoted:
NSString* javaScriptString = #"document.getElementById('Login1_UserName').value='%#';"
"document.getElementById('Login1_Password').value='%#';"
"document.forms['form1'].submit();";
Notice that I've changed value=%# to value='%#' in both cases. This will properly fill-in the input boxes.
Next, call the click() function on the Login button rather than calling submit() on the form:
NSString* javaScriptString = #"document.getElementById('Login1_UserName').value='%#';"
"document.getElementById('Login1_Password').value='%#';"
"document.getElementById('Login1_LoginButton').click()";
this will allow the onclick javascript specified for the Login button to be executed.
You are missing the string quotes.
Try this:
NSString* javaScriptString = #"document.getElementById('Login1_UserName').value='%#';"
"document.getElementById('Login1_Password').value='%#';"
"document.forms['form1'].submit();";