LoginSignup
24
19

More than 5 years have passed since last update.

WebViewでiframeを含むページを表示しようとするとshouldStartLoadWithRequest:が複数回呼ばれる

Last updated at Posted at 2014-10-17

webView:shouldStartLoadWithRequest:navigationType:はWebView内のページ遷移をフックすることができて、戻り値でYESを指定するとそのままリクエストを続行し、NOを指定するとWebViewはそのHTTPリクエストを行わなくなります。
これを利用して、ある特定のドメイン外にアクセスしようとした時はWebViewではなくSafariを開く、という処理を実装していたのですが、このメソッドはページ遷移だけでなく、iframeによる別ページのリクエストでも呼ばれてしまい、ページ内に特定ドメイン外のiframeがあるごとにSafariが開くという問題が発生しました。

解決策

Objective-C
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.absoluteString isEqualToString:request.mainDocumentURL.absoluteString]) {
        // メインコンテンツの読込時
    }
    // ...
}

[1]
Swift
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

    if request.URL.absoluteString == request.mainDocumentURL?.absoluteString {
        // メインコンテンツの読込時
    }
    // ...
}

このようにmainDocumentURLと今読み込もうとしているURLを比較することでiframeかそれ以外かをチェックすることができます。

参考文献

[1] UIWebViewでiframeを含むコンテンツを表示するとshouldStartLoadWithRequestが複数回呼ばれる

24
19
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
24
19