TeeJaay
TeeJaay

Reputation: 144

Observe backForwardList changes of WKWebview

To explain my problem I would like to start with the fundamentals of my project.

We are building an app which employs a web view which loads a lot of different websites (web apps) to form our app package. Those web apps are made with different web tech like ruby or ember/react (single page web app). The later change urls via push state which is problematic for the webviews WKNavigationDelegate as it doesn't recognise any of those url changes. If you load normal http requests (like old rails pages) then everything is fine and well.

In order to know on which page the user is at any time I created a user script which tapped into the pushsstate js prototype and messaged back the url change to the iOS app and even though this is A solution its in my eyes incredibly hacky. So I have been looking for alternatives and I came across the WKWebView.backForwardList which actually records all those push state changes.

The issue I have now is how do I monitor/observe the backForwardList for changes in lets say the currentItem? You can't use KVO to do so as these properties don't support it.

I did however found a possible solution by observing the webview.scrollView.contentSize which for some reason will trigger every time something changes on the screen. It's odd that this observer is fired for every single animation which is running on the screen its almost as if its called on pixel changes of the scrollview. Our web apps are animating all the time as they build with canvas elements for games which means the observer is called a lot and don't feel comfortable to have this running all the time.

Do you know a nicer/neater way to keep track of the changes WKWebView.backForwardList items.

Cheers Thomas

Upvotes: 2

Views: 1049

Answers (1)

TeeJaay
TeeJaay

Reputation: 144

I found the solution which seems obvious but wasn't at the time

// Add observation.
urlObservation = webView?.observe(\.url, changeHandler: { (webView, change) in
      print("Web view URL changed to \(webView.backForwardList.currentItem?.url.absoluteString ?? "Empty")", webView.scrollView.contentSize.width, webView.scrollView.contentSize.height)
})

This seems to track the url changes even though the navigation delegate are NOT triggered in any way.

Upvotes: 3

Related Questions