How to clear WKBackForwardList from WKWebView?

backForwardListWKWebView seems to be read-only, but I have seen people with such pretty magical things to get around this. I need to figure out some way to clear the history of WKWebView. Any ideas how I can do this? So far I have tried several tricks that failed:

  • using keyValue: forKey does not work.
  • using pointer C ->does not work.

I saw people talking about synthesizing properties and extending a class, but I really don’t know how this works and cannot understand. Any other ideas?

+4
source share
2 answers

This code compiles, but I have not tested it ...

WKWebView backForwardList WKBackForwardList.

WKBackForwardList backItem, forwardItem, , , (, , ).

backList forwardList , WKWebView backForwardList. , , .

import Foundation
import WebKit

class WebViewHistory: WKBackForwardList {

    /* Solution 1: return nil, discarding what is in backList & forwardList */

    override var backItem: WKBackForwardListItem? {
        return nil
    }

    override var forwardItem: WKBackForwardListItem? {
        return nil
    }

    /* Solution 2: override backList and forwardList to add a setter */

    var myBackList = [WKBackForwardListItem]()

    override var backList: [WKBackForwardListItem] {
        get {
            return myBackList
        }
        set(list) {
            myBackList = list
        }
    }

    func clearBackList() {
        backList.removeAll()
    }
}

class WebView: WKWebView {

    var history: WebViewHistory

    override var backForwardList: WebViewHistory {
        return history
    }

    init(frame: CGRect, configuration: WKWebViewConfiguration, history: WebViewHistory) {
        self.history = history
        super.init(frame: frame, configuration: configuration)
    }

    /* Not sure about the best way to handle this part, it was just required for the code to compile... */

    required init?(coder: NSCoder) {

        if let history = coder.decodeObject(forKey: "history") as? WebViewHistory {
            self.history = history
        }
        else {
            history = WebViewHistory()
        }

        super.init(coder: coder)
    }

    override func encode(with aCoder: NSCoder) {
        super.encode(with: aCoder)
        aCoder.encode(history, forKey: "history")
    }
}
+1

iOS8 ~ iOS11.

Objective-C

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[wek.backForwardList performSelector:NSSelectorFromString(@"_removeAllItems")];
#pragma clang diagnostic pop

Swift 4

webView.backForwardList.perform(Selector(("_removeAllItems")))

!!!! !!!! WebKit Open Resource, .

+2

Source: https://habr.com/ru/post/1685198/


All Articles