【问题标题】:How can I detect when url of amp page changed with WKWebview如何检测 amp 页面的 url 何时随 WKWebview 更改
【发布时间】:2017-12-15 10:06:36
【问题描述】:

我正在使用 WKWebview 开发简单的网络浏览器。 我可以检测到何时在 SPA 上更改了 URL,例如使用自定义 Javascript 的 trello。

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

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

【问题讨论】:

  • ``` func webView(_ webView: WKWebView, decisionPolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { print(webView.url) print(navigationAction.request.url) ``` 未在 amp 页面中调用

标签: swift wkwebview


【解决方案1】:

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

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

看起来像这样:

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”的新组合。

【讨论】:

  • 可以通过WKWebView中添加的观察者检测视频播放器。你能帮我吗我的问题是stackoverflow.com/questions/55377677/… 我想快速获取在 WKWebView 中播放的视频网址
  • 太棒了!!!太感谢了!所有代表都与首页加载有关,但这救了我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多