5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【iOS】UIWebViewでwebページ内のボタン等を制御する

Last updated at Posted at 2015-04-29

経緯

該当画面はUIWebViewで表示した際、「閉じる」ボタンが効かなかった。
ボタン押下時は閉じるのではなく、一画面戻したかった為、方法を探った。

方法

jsを書き換える為のファイルを用意、プロジェクト内に格納:

JS_WebViewController.txt
window.close = function () {
    history.back();
};

window.close()history.back()で書き換えているだけ、シンプル。

次、
webViewDidFinishLoadで先のファイルを読込、書き換え:

WebViewController.m
// URL読込後
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSError *error = nil;
    NSString *jsFromFile = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]
                                                              URLForResource:@"JS_WebViewController" withExtension:@"txt"]
                                                    encoding:NSUTF8StringEncoding error:&error];
    __unused NSString *jsOverrides = [webView
                                      stringByEvaluatingJavaScriptFromString:jsFromFile];
}

応用

urlスキーマ使えば、objC側でもっと自由にやれる:

JS_WebViewController.txt
window.close = function () {
    open("native://close");
};

同じくwebViewDidFinishLoadで書き換える:

WebViewController.m
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    NSError *error = nil;
    NSString *jsFromFile = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]
                                                              URLForResource:@"JS_WebViewController" withExtension:@"txt"]
                                                    encoding:NSUTF8StringEncoding error:&error];
    __unused NSString *jsOverrides = [webView stringByEvaluatingJavaScriptFromString:jsFromFile];
    

}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *scheme = [request.URL.scheme stringByAppendingString:@":"];
    scheme           = [scheme stringByAppendingString:request.URL.resourceSpecifier];
    if ([scheme isEqualToString:@"native://close"]) {
        
        /*
        *
        * Do Something!!!!!!!!!!!!!!!!!!
        *
        */
        
        [self dismissViewControllerAnimated:YES completion:nil];
        return NO;
    } else {
        return YES;
    }
}

スキーマはrequest.URL.schemerequest.URL.resourceSpecifierで取得して判定してる

参考

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?