OS X WebKit WebView don't show JS Popups - javascript

I just started to develop with xCode because i need a WebView container for a website.
It works so far but i can't logout on the website because there is (in a web browser) a popup window asking if i was sure to logout. I guess it is creates with javascript.
In the Web View settings there is a checkbox labeled "allow popups" but in my app no popup appears after the click.
I've searched for two hours and didn't find something similar related to my problem.

It was a confirm() function of javascript.
I got it to work with:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[webView setUIDelegate:self]; // <------- This is an important part!!!
[[webView preferences] setJavaScriptEnabled:YES];
[[webView preferences] setJavaScriptCanOpenWindowsAutomatically:YES];
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:homeURLString]]];
}
and
- (BOOL)webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
NSInteger result = NSRunInformationalAlertPanel(NSLocalizedString(#"JavaScript", #""), // title
message, // message
NSLocalizedString(#"OK", #""), // default button
NSLocalizedString(#"Cancel", #""), // alt button
nil);
return NSAlertDefaultReturn == result;
}
More Info here and here.

Related

UIWebview Print option

I've created a container iOS app(objective c) which has only one webview. The webview is loaded with a website which is not owned by me. The website that i am accessing from webview has a print button. Tapping on it doesnt do anything. The same website when accessed via mobile browser works fine. I tried with several other websites with print button . It acts the same.
I wrote the following code for airprint. So whenever a native print button is clicked the following code is executed and it works fine.
But how can i execute this code when user clicks on print button on website ???
In other ways is there a way to detect if user clicks the print button on any website ??
UIPrintInfo *pi = [UIPrintInfo printInfo];
pi.outputType = UIPrintInfoOutputGeneral;
pi.jobName = webView.request.URL.absoluteString;
pi.orientation = UIPrintInfoOrientationPortrait;
pi.duplex = UIPrintInfoDuplexLongEdge;
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.printInfo = pi;
pic.showsPageRange = YES;
pic.printFormatter = webView.viewPrintFormatter;
[pic presentAnimated:YES completionHandler:^(UIPrintInteractionController *pic2, BOOL completed, NSError *error) {
// indicate done or error
}];

Close keyboard in UIWebView

I am working on a web application which will be accessed from iOS UIWebView. When user touches an input text field, the UIWebView automatically opens the keyboard. Everything is fine up to this point.
Now when user taps anywhere on the page I want to dismiss the keyboard. What would be the method to do this.
I tried following code but that did not work for me -
$(document).on("tap", function (e) {
document.activeElement.blur();
});
Try something like
document.foo.bar.myinput.blur();
I think it will help you out.
[myWebView stringByEvaluatingJavaScriptFromString:#"document.activeElement.blur()"];
If you want a non-Javascript option:
Start by adding a UITapGestureRecognizer to your UIWebView in your ViewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(dismissWebViewKeyboard)];
[self.webView addGestureRecognizer:tapGesture];
//the rest of your initialization code goes here
}
And then, add your dismissWebViewKeyboard method, which just ends editing on your UIWebView:
- (void)dismissWebViewKeyboard
{
[self.webView endEditing:YES];
}
And that should do it!

Parse a javascript window.close() function from a web page in xcode

I am writing an application for my parent's photo booth business.
They upload all the event pictures to different Flickr photosets on their account, and on the website they have an albums page with a collection of all their events so that people from the events can go and see all their photo strips, as well as each individual picture and then download them for themselves.
Most of their traffic is from mobile devices (my brother wrote the website specifically to fit mobile device screens as well as normal computer screens just as well); however, downloading and sharing the images is easier through an app (thanks to Apple's iOS 6 UIActivityViewController and UICollectionView).
So I'm writing the app that makes it easier to view and share the pictures. I have most of it done and working great! However, it currently only supports iOS 6 and I'm trying to include iOS 5. It only supports iOS 6 because I am using a UICollectionView to display the pictures from events. However, since iOS 5 does not include collection views I use a web view of our albums web page which displays all images.
When you select an image, you can choose a size of the image to view. When you pick a size, it opens a new tab, that includes the image and two links. One to download the image, and one to close the tab. The two links are within an unordered list and each link is its own list item.
This is the link to download the image:
Download Image
And the closing tab link has a tag of:
<a href="javascript:window.close();">
I've seen that you can use the webView's delegate method shouldStartLoadWithRequest: and then:
if ([[[request URL] absoluteString] hasPrefix:#"/downloadImage.php"]) {
UIImageWriteToSavedPhotosAlbum(imageToBeSaved, nil, nil, nil);
return NO;
} else if ([[[request URL] absoluteString] hasPrefix:#"javascript"]) {
[webView goBack];
return NO;
} else { return YES; }
Which would make it do those functions when the links are clicked...right?
These do not work though. And I'm not sure how to make them work.
I am searching for the correct way to use this method, or some alternative method, if possible, to use Objective-C to do the equivalent of what the html normally does.
I figured out a way to do basically what I wanted. Rather than let the webView open a new page when you selected an image size. I set the size links to just download the image right there using this code:
// for links thats contain the displayImage.php do not allow user interaction
if ([[[request URL] absoluteString] hasPrefix:#"http://www.remembermephotobooths.com/displayImage.php?link="]) {
//scan through the link url get the image link so that I can download it
NSMutableArray *substring = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:[[request URL] absoluteString]];
[scanner scanUpToString:#"http://farm9" intoString:nil]; // Scan all characters after and including http://farm9 because all download links begin with http://farm9
while(![scanner isAtEnd]) {
NSString *string = nil;
[scanner scanString:#"&title=" intoString:nil]; // Scan up to &title
if([scanner scanUpToString:#"&" intoString:&string]) {
[substring addObject:string];
}
[scanner scanUpToString:#".jpg" intoString:nil]; // Scan all characters up to and including .jpg because all images are jpegs
}
// save image to photo library
UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:substring[0]]]], nil, nil, nil);
// let the user know the image was saved
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
[hud setMode:MBProgressHUDModeText];
hud.labelText = #"Saved Image!";
[hud setMinShowTime:1.5];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[substring release];
return NO; //this is what disables the links usual code and has it run my code instead
}
else { //all other links are enabled
return YES;
}

UIWebView: Can I disable the javascript alert() inside any web page?

I am using UIWebView to load a URL.
Inside the page of that URL, it uses alert("whatever msg") as JavaScript. My UIWebView will pop up a window and show that alert message.
Is there a way to disable this kind of popup window or JavaScript alert window?
Add this after your web view has loaded its content
[MyWebView stringByEvaluatingJavaScriptFromString:#"window.alert=null;"];
You can bind window.alert to another function. So:
window.alert = function() {
//does nothing so effectively "disables" alert
};
Make sure you do this before you call any alerts. The neat thing about this is you can customize the way you display messages to the user. So you could override window.alert to log to the console (for debugging purposes) or you can render it on the page (with a lightbox or something similar).
Since a UIWebView translates all Javascript alerts into native UIAlertViews it is fairly simple to block it on the native end. Looking into UIAlertView.h there is only one public method for showing an alert which is conveniently called: - (void)show;.
#interface UIAlertView (Blocker)
#end
#import "UIAlertView+Blocker.h"
#implementation UIAlertView (Blocker)
- (void)show {
return;
}
#end
You can find the answer here: https://stackoverflow.com/a/21698251/2377378
let script = """
window.alert=window.confirm=window.prompt=function(n){},
[].slice.apply(document.querySelectorAll('iframe')).forEach(function(n){if(n.contentWindow != window){n.contentWindow.alert=n.contentWindow.confirm=n.contentWindow.prompt=function(n){}}})
"""
webView.evaluateJavaScript(script, completionHandler: nil)

window opener close issue for javascript

I have a problem with browsers window managament with javascript.
I have two page in my proof of concept application. First page contains login information (username, password, login button etc.) and second page is a managament screen. I need that when the user pressed to the login button on the login screen it open to main screen and main screen must be open new window without full screen. I mean close, minimize, maximize buttons and bottom bar of the windows os must be stayed on the screen.
During opening the new window on the login screen, it must be close itself automatically. I have found many example script but every script giving same results to me.
For example; following script solving my problem but same problems continue for me,
firefox does't close opener window it self,
ie 6.0 closing opener window - it's working
ie 7.0 - 8.0 before the close it self it asking "The webpage you are viewing is trying to close the window".
window.open("Content/StartPage.aspx", windowName, "menubar=0, location=0, resizable=1, status=1, width=" + screen.width + ",height=" + screen.height);
if (window.name != windowName) {
var me = window.self;
me.opener = window.self;
me.close();
}
How can i open new window and close the opener with above requirements without ask browsers question ?
Thank you.
You cannot do it according the security assurance of browser, there are some action which doesn't allow to be managed directly via javascript without user interference.
Try something like this in your new window, on the body onload:
function closeParent()
{
try
{
var op = window.opener;
op.opener = self;
op.close();
}
catch(er) {}
}
Still, this solution isn't perfect, I only got it to work in Internet Explorer, and even then, I got a warning popup for closing the parent window. This might be something that can't feasibly be solved.

Categories