swift - 每当用户移动到其他页面时如何从 webview 获取 url

标签 swift url webview notifications nsurl

每当 URL 更改时,如何从 webView 获取 URL?

我想在当前 URL 更改时更改按钮颜色。所以我需要一直检查当前的 URL。

而且我还想获​​取字符串形式的 URL 值。

我尝试了下面的代码,但它根本不起作用。

NotificationCenter.default.addObserver(self, selector: #selector(urlChecker), name: NSNotification.Name.NSURLCredentialStorageChanged, object: webView)

最佳答案

你可以使用:

1。解决方案

UIWebViewDelegate

https://developer.apple.com/reference/uikit/uiwebviewdelegate/1617945-webview

optional func webView(_ webView: UIWebView, 
  shouldStartLoadWith request: URLRequest, 
       navigationType: UIWebViewNavigationType) -> Bool

UIWebViewNavigationType:

https://developer.apple.com/reference/uikit/uiwebviewnavigationtype

不要忘记返回true

case linkClicked

User tapped a link.

case formSubmitted

User submitted a form.

case backForward

User tapped the back or forward button.

case reload

User tapped the reload button.

case formResubmitted

User resubmitted a form.

case other

Some other action occurred.

2。解决方案

注入(inject) Javascript JavaScript MessageHandler

(归功于Vasily Bodnarchuk)

解决方案在这里:https://stackoverflow.com/a/40730365/1930509

Swift 3 example.

Description

The script is inserted into page which will displayed in WKWebView. This script will return the page URL (but you can write another JavaScript code). This means that the script event is generated on the web page, but it will be handled in our function:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {...}

Full Code example

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView = WKWebView()
    let getUrlAtDocumentStartScript = "GetUrlAtDocumentStart"
    let getUrlAtDocumentEndScript = "GetUrlAtDocumentEnd"
     override func viewDidLoad() {
             super.viewDidLoad()

            let config = WKWebViewConfiguration()
            config.addScript(script: WKUserScript.getUrlScript(scriptName: getUrlAtDocumentStartScript),
 scriptHandlerName:getUrlAtDocumentStartScript, scriptMessageHandler:
 self, injectionTime: .atDocumentStart)
            config.addScript(script: WKUserScript.getUrlScript(scriptName: getUrlAtDocumentEndScript),
scriptHandlerName:getUrlAtDocumentEndScript, scriptMessageHandler:
self, injectionTime: .atDocumentEnd)


             webView = WKWebView(frame:  UIScreen.main.bounds, configuration: config)
            webView.navigationDelegate = self
             view.addSubview(webView)
        }

     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         webView.loadUrl(string: "http://apple.com")
    }
}
extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        switch message.name {

            case getUrlAtDocumentStartScript:
                print("start: \(message.body)")

            case getUrlAtDocumentEndScript:
                print("end: \(message.body)")

            default:
                break;
        }
    }
}

extension WKUserScript {
    class func getUrlScript(scriptName: String) -> String {
        return "webkit.messageHandlers.\(scriptName).postMessage(document.URL)"
    }
}

extension WKWebView {
    func loadUrl(string: String) {
        if let url = URL(string: string) {
            load(URLRequest(url: url))
        }
    }
}
 extension WKWebViewConfiguration {
        func addScript(script: String, scriptHandlerName:String, scriptMessageHandler: WKScriptMessageHandler,injectionTime:WKUserScriptInjectionTime) {
             let userScript = WKUserScript(source: script, injectionTime: injectionTime, forMainFrameOnly: false)
             userContentController.addUserScript(userScript)
             userContentController.add(scriptMessageHandler, name: scriptHandlerName)
        }
    }

Info.plist

add in your Info.plist transport security setting

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Result

enter image description here

Resources ##

Document Object Properties and Methods

关于swift - 每当用户移动到其他页面时如何从 webview 获取 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908595/

相关文章:

ios - 如何在 UIsearchbar iOS swift 中为文本字段添加自定义图像

security - 引用 header 中的 CDN 和个人身份信息

c# - 如何使用网络浏览器在链接列表中导航?

android - 将 webview 重置为初始状态

ios - 检查特定的手势识别器

swift - Swift Playground 中的段错误

javascript - Android webview - XMLHttpRequest 无法加载 Origin <url> 是 Access-Control-Allow-Origin 不允许的

android - 统一,通过 WebView 获取youtube网址,然后统一播放视频

swift - 为什么我需要将属性强制转换为与该属性具有相同签名的泛型方法?

javascript - 灰盒图像未加载可能存在 URL 问题?