iOS - Webview - Notify Javascript when an NSNotification is received - javascript

I was wondering if anyone knew how to do this. I have a bunch of NSNotifications and I'd like to create listeners in Javascript, embedded in a UIWebView, that will get executed when the NSNotifications are received.
I know this is possible using PhoneGap and the method sendPluginResult, but I was wondering if there was another way of doing it without cordova.
Thanks

Create your listener outside the UIWebView and send the stringByEvaluatingJavaScriptFromString message to your web view.
- (void)registerObserver
{
NSArray *names = [NSArray arrayWithObjects:
#"FirstNotification", #"SecondNotification", #"ThirdNotification", nil];
for (NSString *name in names)
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(notificationReceived:)
name:#"NotificationName"
object:nil];
}
}
- (void)notificationReceived:(NSNotification *notification)
{
NSString *js = [NSString stringWithFormat:
#"notificationReceived('%#');", notification.name];
[self.webView stringByEvaluatingJavaScriptFromString:js];
}

in the call back NSNotification method call this:
[yourwebview stringByEvaluatingJavaScriptFromString:#"methodName()"];
and create that "methodname" in your javascript code

Related

WkWebView JavaScript script not working

My Goal is to send data from iOS device to WkWebView. After researching on how to do this task I get to know that it can be done via executing JavaScript function via WkWebView, therefore, I tried calling just a simple alert function:
#interface UIWebViewController () <WKNavigationDelegate, WKUIDelegate>
#end
WKWebView *webView;
-(void)webView:(WKWebView )webView didFinishNavigation:(WKNavigation )navigation{
NSString* javascriptString = #"alert('Hi');";
[webView evaluateJavaScript:javascriptString completionHandler:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
webView.navigationDelegate = self;
}
Unfortunately I am not able to see any alert with that code?
Can you let me know what kind of silly mistake I am doing in the above code?

WKWebview javascript works on simulator but doesn't work on device if the view isn't on the screen

I'm using a WKWebview to run javascript scripts.
I am not using JSContext et.al since I need the javascript context to be able to perform XHTTP requests which aren't possible with JSContext alone.
This view is not added to the view hierarchy and I have no interest to do so.
The WKWebview is only used for its ability to run JS code in its engine.
The javascript code is working exactly as expected on the simulator.
The exact same code will also work in the context of certain other applications which I've tested with.
But for some reason in certain applications the WKWebview will not perform the javascript unless the WKWebview is added to the view hierarchy. The following code will work as expected. If removing the #warning code , stops working as expected
-(void)connect {
//TODO: Handle multiple connect calls
WKUserContentController *userContentController = [WKUserContentController new];
[self addScriptMessageHandlersForSocketEvents:userContentController];
NSString *socketFileContent = [self.class socketIOScript];
WKUserScript *socketIOScript = [[WKUserScript alloc] initWithSource:socketFileContent
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:socketIOScript];
NSString *bridgeJs = [self.class bridgeScript];
WKUserScript *bridgeScript = [[WKUserScript alloc] initWithSource:bridgeJs
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:bridgeScript];
NSMutableDictionary *d = [NSMutableDictionary new];
for (NSURLQueryItem *item in _parameters) {
d[item.name] = item.value;
}
NSString *params = json(d);
NSString *socketURLScript = [NSString stringWithFormat:#"createSocket(%#,%#);log('created script')",stringify(_url),params];
WKUserScript *createSocket = [[WKUserScript alloc] initWithSource:socketURLScript
injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
forMainFrameOnly:NO];
[userContentController addUserScript:createSocket];
WKWebViewConfiguration * wkconfiguration = [WKWebViewConfiguration new];
wkconfiguration.userContentController = userContentController;
_wv = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:wkconfiguration];
#warning REMOVE THIS AND THE WKWebview stops working on some devices (NOT ALL DEVICES) and works in some applications as expected
[[UIApplication sharedApplication].keyWindow addSubview:_wv];
// END REMOVE THIS
_wv.navigationDelegate = self;
dispatch_group_enter(_loadedSemaphore);
[_wv loadHTMLString:#"<h1></h1>" baseURL:nil];
}
did you implement all the delegate methods for WKWebView ?

Using Native UISearchBar to search a place on WKWebView

I'm still a beginner with Objective C
I developed a website using cakephp and I used a paid api for the map
Now I'm trying to build an iOS app but they don't have an iOS api so I only need to display the map into WKWebView
I removed all the buttons and created native buttons
I succeed to to inject JS to the native buttons using evaluateJavaScript and it works fine
But now I created an UISeachBar on the navigation bar and I'm using
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
I want to send the searchText to a JS function and then return an array
the problem is that when I created a JS function just for testing I get this message when I type String :
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred}
But when I type numbers it works fine
My Objc code :
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSString *function = [[NSString alloc] initWithFormat: #"getSuggest(%#)", searchText];
[_webView evaluateJavaScript:function completionHandler:^(NSString *result, NSError *error)
{
NSLog(#"Error %#",error);
NSLog(#"Result %#",result);
}];
}
My JS code :
var getSuggest = function(searchText) {
return searchText;
}
you have to embed the searchText into "" for the js function call:
NSString *function = [[NSString alloc] initWithFormat: #"getSuggest(\"%#\")", searchText];

EasyJSWebView breaks when reloading the webview

I have been implementing EasyJSWebView into a project that pops up a web view on the receipt of a push message. This works fine for the most part, until you want to reload the current webview. At that point the functionality of EasyJSWebView breaks and the javascript in the webpage cannot communicate with the objective C running in the app.
This is the code I'm using to add the interface to the webview and then load the page on the view.
_webView.delegate = self;
javaScriptInterface* interface = [javaScriptInterface new];
[self.webView addJavascriptInterfaces:interface WithName:#"interface"];
interface.webView = self;
[interface release];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"mywebpage.com"]]];
If I call another loadrequest on the webview, even if it is to the same page, this stops working. I have tried adding another interface object to the webview before a reload but that doesn't seem to do anything either.
At the moment I am destroying the current webview and creating a new one each time I need to do a reload or another push message is received.
Is there any fix or workaround to this? I would like to be able to use one webview for everything and not worry if it gets reloaded or not.
There's a bug in the original EasyJSWebView repository.
Just use the fork from here: https://github.com/andiradulescu/EasyJSWebView
I'm not sure if this is the best way to solute the issue, but it works in my project. My method is to create an new UIWebView before every reload or redirect request. Below is the details:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
//'isNotFirstLoad' marks if it is the fisrt load.
if (isNotFirstLoad) {
//create an new webview
CGRect frame = _myWebView.frame;
[_myWebView removeFromSuperview];
_myWebView = [[EasyJSWebView alloc] initWithFrame:frame];
[self.view addSubview:_myWebView];
//init the new webview
_webView.delegate = self;
javaScriptInterface* interface = [javaScriptInterface new];
[self.webView addJavascriptInterfaces:interface WithName:#"interface"];
[_myWebView loadRequest:request];
//reset the firstload flag to load the new request
isNotFirstLoad = NO;
return NO;
}
isNotFirstLoad = YES;
return YES;
}

Can I handle alert inside UIWebViewDelegate?

<script language="javascript">
alert("Hell! UIWebView!");
</script>
I can see the alert message inside my UIWebView but can I handle this situation?
Update:
I'm loading a web-page into my UIWebView:
- (void)login {
NSString *requestText = [[NSString alloc] initWithFormat: #"%#?user=%#&password=%#", DEFAULT_URL, user.name, user.password]; // YES, I'm using GET request to send password :)
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestText]];
[webView loadRequest:request];
}
The target page contain a JS. If user name or password is incorrect this JS show alert.
I have not any access to its sources.
I want to handle it inside my UIWebViewDelegate.
A better solution to this problem is to create a Category for UIWebView for the method
webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:
So that you can handle the alert event in any way that you'd like. I did this because I don't like the default behavior of UIWebView when it puts the filename of the source in the UIAlertView title. The Category looks something like this,
#interface UIWebView (JavaScriptAlert)
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;
#end
#implementation UIWebView (JavaScriptAlert)
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
UIAlertView* dialogue = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil];
[dialogue show];
[dialogue autorelease];
}
#end
This seems to do it:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *ctx = [webView valueForKeyPath:#"documentView.webView.mainFrame.javaScriptContext"];
ctx[#"window"][#"alert"] = ^(JSValue *message) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"JavaScript Alert" message:[message toString] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
};
}
Note: only tested on iOS 8.
If by "contain a flash" you mean the page you're loading into your web view has an Adobe Flash movie in it, you're out of luck, I'm afraid. Mobile Safari doesn't support Flash, and most likely never will.
In the general case, if you want JavaScript running in a web view to communicate with the native app hosting it, you can load fake URLs (for example: "myapp://alert?The+text+of+the+alert+goes+here."). That will trigger the webView:shouldStartLoadWithRequest:navigationType: delegate method. In that method, inspect the request, and if the URL being loaded is one of these internal communications, trigger the appropriate action in your app, and return NO.

Categories