如何使用 WKWebview 检测 amp 页面的 url 何时更改 [英] How can I detect when url of amp page changed with WKWebview

查看:28
本文介绍了如何使用 WKWebview 检测 amp 页面的 url 何时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WKWebview 开发简单的网络浏览器.我可以使用自定义 Javascript 检测到像 trello 一样在 SPA 中更改 url 的时间.

I'm developing simple web browser with WKWebview. I can detect when url changed at SPA like trello with custom Javascript.

这种方式在放大器页面中不起作用.(谷歌加速移动页面)我尝试将 print("webView.url") 放到所有 WKNavigationDelegate 函数中但我无法检测到 amp page url 的变化.

That way will not work In amp page. (Accelerated Mobile Pages of Google) I tried put print("webView.url") to all of WKNavigationDelegate function But I couldn't detect change of amp page url.

但是 webView 有 amp 页面 url ,我想将 amp 页面 url 保存到本地商店.

But webView has amp page url , I'd like to save amp page url to local store.

推荐答案

同样的问题.不幸的是,WKWebView 仅在发生完整页面加载时触发其功能.

Same issue. Unfortunately WKWebView only fires its functions when a full page load happens.

所以我们要做的是在 WebKit.url 属性上使用 Key Value Observing.

So what we have to do instead is use Key Value Observing on the WebKit.url property.

看起来像这样:

import AVFoundation
import UIKit
import WebKit
import MediaPlayer

class ViewController: UIViewController, WKNavigationDelegate {
  @IBOutlet weak var webView: WKWebView!

  override func viewDidLoad() {
    super.viewDidLoad()

    webView.navigationDelegate = self

    self.webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
    self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)

    self.webView.load(URLRequest(url: "https://google.com"))
  }

  override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == #keyPath(WKWebView.url) {
      print("### URL:", self.webView.url!)
    }

    if keyPath == #keyPath(WKWebView.estimatedProgress) {
      // When page load finishes. Should work on each page reload.
      if (self.webView.estimatedProgress == 1) {
        print("### EP:", self.webView.estimatedProgress)
      }
    }
  }

wkWebkitView 中的每个附加导航都应导致触发### URL"和### EP"的新组合.

Each additional navigation in the wkWebkitView should cause a new combo of "### URL" and "### EP" to fire off.

这篇关于如何使用 WKWebview 检测 amp 页面的 url 何时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆