39
36

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.

WKWebViewでJavaScriptを読み込み前後に仕込むサンプル

Last updated at Posted at 2014-08-31

WKWebViewをinit時にJavaScriptを設置します。設置したJavaScriptはページ読み込みのたびに実行されます。

window.webkit.messageHandlers.yourKeyPath.postMessage("文字列/配列など");
上記のJavaScriptを使うと、userContentController:didReceiveScriptMessage:が応答するので、yourKeyPath部分をもとに処理できます。

サンプルとして新規作成、"Single View Application"テンプレートからViewController.mに以下を貼り付けると試せます。

結果としてデバッグエリアにUserAgentが表示されるはずです。

#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()
<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController
            
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // JavaScript
    // didGetUserAgentの部分は後で使用する(任意のキャメルケース)
    NSString *getUserAgent
    = @"window.webkit.messageHandlers.didGetUserAgent.postMessage(window.navigator.userAgent);";
    
    // JavaScript挿入タイミング: ページの読み込み前かあとか
    // injectionTime: WKUserScriptInjectionTimeAtDocumentStart / WKUserScriptInjectionTimeAtDocumentEnd
    WKUserScript *getUserAgentScript
    = [[WKUserScript alloc] initWithSource:getUserAgent
                             injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                          forMainFrameOnly:YES];
    
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addUserScript:getUserAgentScript];
    [userContentController addScriptMessageHandler:self name:@"didGetUserAgent"];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];
    
    NSString *urlString = @"http://www.yahoo.co.jp/";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_webView loadRequest:request];

}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    id body = message.body;
    NSString *keyPath = message.name;
    
    if ([body isKindOfClass:[NSString class]]) {
        if ([keyPath isEqualToString:@"didGetUserAgent"]) {
            NSLog(@"UserAgent: %@", body);
        }
    }
}


@end

こちらも設定しておくといいと思います。
WKWebViewでwindow.webkit.messageHandlersが効かないサイトへの対処法

39
36
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
39
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?