Reputation: 2188
I developed hybrid iOS application with Swift and want to detect history.pushstate() in WKWebView. I did override WKWebView's methods, but I couldn't detect anything.
Is there a way or trick to detect history.pushstate()
Upvotes: 6
Views: 2099
Reputation: 121
You can observe WKWebView.url
through key-value observing
var urlObservation: NSKeyValueObservation?
...
let webView = WKWebView(...)
urlObservation = webView.observe(\.url, changeHandler: { webView, change in
print("url changed")
})
It seems that Firefox for iOS is also using this way.
Upvotes: 3
Reputation: 16777
This is certainly a workaround, but if you are allowed to edit properties of built-in objects (like in most browsers) you can wrap both functions and use an intercepting handler to track when they are called:
function track (fn, handler) {
return function interceptor () {
handler.apply(this, arguments)
return fn.apply(this, arguments)
}
}
history.pushState = track(history.pushState, function (state, title, url) {
// do something with `state, `title`, and `url`
console.log('pushState called with:', { state: state, title: title, url: url })
})
history.replaceState = track(history.replaceState, function (state, title, url) {
// do something with `state, `title`, and `url`
console.log('replaceState called with:', { state: state, title: title, url: url })
})
history.pushState(null, 'Title 1', '/example-page')
Upvotes: 3