Load JS Function stringByEvaluatingJavaScriptFromString with IOS - javascript

I have a simple javascript function with two variables for the geolocation. I need to pass two variables that I already have in my iOS application to this javascript function.
When I send the code via console in the browser everything is OK:
geoCallBackSuccess({coords:{'longitude':9.598470,'latitude':50.903697}})
Is my code correct?
In the simulator I see no effect...
NSString * param = #"{coords:{'longitude':9.598470,'latitude':50.903697}}";
NSString * jsCallBack = [NSString stringWithFormat:#"geoCallBackSuccess(%#)",param];
NSLog(#"viewDidLoad - jsCallBack: %#", jsCallBack);
[self.offerUrl stringByEvaluatingJavaScriptFromString:jsCallBack];
Log:
viewDidLoad - jsCallBack:
geoCallBackSuccess({coords:{'longitude':9.598470,'latitude':50.903697}})
For example, this works for me:
[self.offerUrl stringByEvaluatingJavaScriptFromString:#"document.getElementById(\"anzeige\").innerHTML=\"Hello World\";"];
I want to do the same as I do in Android:
#java...
public void getLocation() {
// magic
if (locationOk) {
webview.loadUrl("javascript:geoCallBackSuccess({coords:{'longitude':9.598470,'latitude':50.903697}})");
} else { webview.loadUrl("javascript:geoCallBackError({code:})");
}
}
Thanks

I believe you are missing just one semi colon in the string, semicolon after function name -
NSString * jsCallBack = [NSString stringWithFormat:#"geoCallBackSuccess(%#);",param];

Related

How do I repurpose JSContext in UIWebView to WKScriptMessage for WKWebview

I want to convert a UIWebView library to use WkWebview. The remaining piece is switching out JSContext because the valueForKeyPath doesn't work anymore. So how do I rewrite something like the following to use WKScriptMessage as the other SO link suggests? (swift or ObjC answer is fine) How to get JSContext from WKWebView
JSContext *ctx = [webView valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
ctx[#"contentPasteCallback"] = ^(JSValue *msg) {
__weak typeof(weakSelf) StrongSelf = weakSelf;
StrongSelf.editorPaste = YES;
};
[ctx evaluateScript:#"document.getElementById('zss_editor_content').addEventListener('paste', contentPasteCallback, false);"];
I have converted UIWebView to WKWebView for Editor. I have created fork from this Github Link. The link to my demo can be found here.
Ok I figured it out. See the PR https://github.com/nnhubbard/ZSSRichTextEditor/pull/243
Basically you inject javascript to start the listeners. The key here is to pass the function which calls webkit using postMessage and use the same name, in my case 'jsm' as what was setup when you create the WKUserContentController object
NSString *pasteListener = #"document.getElementById('zss_editor_content').addEventListener('paste', function() {window.webkit.messageHandlers.jsm.postMessage('paste');});";
[self.editorView evaluateJavaScript:pasteListener completionHandler:^(NSString *result, NSError *error) {
if (error != NULL) {
NSLog(#"%#", error);
}
}];
and then you listen for the response in the userContentController: didReceiveScript delegate method from WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSString *messageString = (NSString *)message.body;
if ([messageString isEqualToString:#"paste"]) {
self.editorPaste = YES;
}

UIWebView not calling my Javascript function

I am aware that this question is already posted lot many times. But none of them are helping me to solve my issue. Please consider reading entire question before downvote :-)
So, for I have below lines of code
- (void)viewDidLoad {
[super viewDidLoad];
NSURL * url = [NSURL URLWithString: #"https://www.w3schools.com/code/tryit.asp?filename=FEGU9IV4SAK8"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
self.webView.delegate = self;
[self.webView loadRequest:request];
}
#pragma mark - UIWebView Delegates
- (void) webViewDidFinishLoad:(UIWebView *)webView {
NSString * jsString = [NSString stringWithFormat:#"test()"];
[webView stringByEvaluatingJavaScriptFromString:jsString] ;
//This code is working. Able to prompt "Hello"
// jsString = [NSString stringWithFormat:#"alert('Hello');"];
// [webView stringByEvaluatingJavaScriptFromString:jsString] ;
}
- (BOOL)webView:(UIWebView *)webView
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType;
{
// ignore legit webview requests so they load normally
if (![request.URL.scheme isEqualToString:kSchemeName]) {
return YES;
}
// look at the actionType and do whatever you want here
if ([actionType isEqualToString:kJSActionForPay]) {
//Call objective-c method - Success
}
// make sure to return NO so that your webview doesn't try to load your made-up URL
return NO;
}
So, Far I have tried / understood.
[1] Call JS function only after web view loaded. (used delegate)
[2] Able to prompt "Hello" from
[webView stringByEvaluatingJavaScriptFromString:#"alert('Hello')"] ;
[3] Changes done in HTML side
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
<script>
function test() {
alert("Started");
}
</script>
</html>
Please help to find out what I am missing in HTML Side ? or In my native Objc?
EDIT 1:
As #Andy suggested, I loaded html from local. Then I am able to call JS function "test()"
You should not use the w3schools editor to be the source html for your project. The url you tried to visit not only contains your content but also the scripts used by w3schools. Instead, you should put your html file on your own server or a .html file inside your project. Then, you can call the test() method.

Running javascript method from local file, very slow in some iOS devices. iPad mini, iPad 3

I am trying to call javascript method from a xamarin ios project. JS files are in the project folder.
At first I have tried to use UIWebView. It was working in simulators and most of the devices. I did something like this...
First I load the html file containing js methods.And then i call js method.
webview.LoadRequest (new NSUrlRequest (new NSUrl (address)));
webview.EvaluateJavascript (String.Format ("Client.authenticateUser('{0}','{1}','{2}','{3}');", email, password, onSuccess, onFailure));
It was ok in all simulators. However, when I tested in my ipad mini, the response from the js methods came after a big delay (nearly 2 min).
Then i found that WKWebview is better than UIWebview and i tried to use that also. But same result, js methods are giving response with great delay in ipad mini and ipad 3.
Here is my code using WKWebview
loginBtn.TouchUpInside += delegate {
var userController = new WKUserContentController ();
userController.AddScriptMessageHandler (this, "myapp");
var config = new WKWebViewConfiguration {
UserContentController = userController
};
wkwebview = new WKWebView (new CGRect (0, 0, 0, 0), config);
wkwebview.NavigationDelegate = this;
string index = Path.Combine (NSBundle.MainBundle.ResourcePath,"www/main.html");
string webAppFolder = Path.Combine (NSBundle.MainBundle.ResourcePath, "www");
wkwebview.LoadFileUrl (new NSUrl ("file://" + index), new NSUrl("file://"+ webAppFolder, true));
};
[Export ("webView:didFinishNavigation:")]
public void DidFinishNavigation (WKWebView webView, WKNavigation navigation)
{
string email = emailField.Value;
string password = passwordField.Value;
webView.EvaluateJavaScript (new NSString (String.Format ("Client.newAuthenticateUser('{0}','{1}','{2}','{3}');", email, password, "onSuccess", "onFailure")), (result, error) => {
});
}
public void DidReceiveScriptMessage (WKUserContentController userContentController, WKScriptMessage message)
{
var msg = message.Body.ToString ();
System.Diagnostics.Debug.WriteLine (msg);
}
What may be the solution for this? Is there anything I am missing to implement this? Or is it for device lower configurations? Please help.

UIWebView vs WebView Javascript Injection

Im trying to execute javascript on iPhone by stringByEvaluatingJavaScriptFromString,
i made script
function execute() {
//dosent matter
alert('works');
}
execute();
This script works fine while using in developer console in safari.
But this way :
[self.webView1 stringByEvaluatingJavaScriptFromString:#"javascript: function execute() { alert('works');}execute();"];
Dosent work, i dont see alert, i tried also without "javascript:"
Thats confusing because im using stringByEvaluatingJavaScriptFromString with succes but without using function declaration.
[self.webView1 stringByEvaluatingJavaScriptFromString:#"alert('check');"];
works fine
If anyone is looking for answer, i have noticed that some functions could not work properly without putting them in file.js and then execute by using:
- (void)injectJavascript:(NSString *)resource {
NSString *jsPath = [[NSBundle mainBundle] pathForResource:resource ofType:#"js"];
NSString *js = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:NULL];
[self.webView1 stringByEvaluatingJavaScriptFromString:js];
}

Call javascript - click() in a WebView from Cocoa Objective-C code

In a MacOS X application, I create a Window containing a WebView.
The WebView is initialized on a html page that contains an anchor:
Go To Google.
I would like to click on that link from another class.
It seems clear that a simple javascript code would do the trick: document.getElementById("myLink").click();
So, I wrote that small objective-c code that should do it:
NSString *cmd = #"document.getElementById(\"myLink\").click();";
id result = [[attachedWebView windowScriptObject] evaluateWebScript:cmd];
if ([result isMemberOfClass:[WebUndefined class]]) {
NSLog(#"evaluation of <%#> returned WebUndefined", cmd)
But I can't make it work.
If anybody has an idea, that would really help.
I think it is nothing todo with webview, but just your javascript.
Does it work if you try it in Safari's console? I wouldn't expect it to as you can only click() input elements (buttons) reliably cross-browser. A JQuery click() should work tho.
see How do I programmatically click a link with javascript?
So here is the solution I used.
Created a file: WebAgent.js containing the following code:
function myClick(id) {
var fireOnThis = document.getElementById(id);
var evObj = document.createEvent('MouseEvents');
evObj.initEvent( 'click', true, true );
fireOnThis.dispatchEvent(evObj);
}
And the following code in my objective-c class
// load cmd.js
NSString *path = #"/code/testagent/WebAgent/WebAgent/WebAgent.js";
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[[self attachedWebView ]stringByEvaluatingJavaScriptFromString:jsCode];
//do the click
NSString * anchorId = #"myId";
NSString *call = [NSString stringWithFormat:#"WebAgent_click('%#')",anchorId];
[[self attachedWebView] stringByEvaluatingJavaScriptFromString:call];
NB: I used this solution to have the JS code in a specific file, as I expect to have more JS code in the future.
Thanks for your help.

Categories

Resources