WKWebview详解一,基础API

WKWebview

{
    /*! 初始化wkwebview时可设置的一个参数 */
    @NSCopying open var configuration: WKWebViewConfiguration { get }

    
    /*! wkwebview的导航代理 */
    weak open var navigationDelegate: WKNavigationDelegate?

    
    /*! wkwebview的UI界面代理 */
    weak open var uiDelegate: WKUIDelegate?

    
    /*! 控制wkwebview返回前进查看网页对象,此对象包含整个导航栈,向前,向后等属性 */
    open var backForwardList: WKBackForwardList { get }

    
    /*! @abstract Returns a web view initialized with a specified frame and
     configuration.
     @param frame The frame for the new web view.
     @param configuration The configuration for the new web view.
     @result An initialized web view, or nil if the object could not be
     initialized.
     @discussion This is a designated initializer. You can use
     @link -initWithFrame: @/link to initialize an instance with the default
     configuration. The initializer copies the specified configuration, so
     mutating the configuration after invoking the initializer has no effect
     on the web view.
     初始化一个wkwebview使用参数,==注意使用configuration初始化一个wkwebview时,configuration的属性要在初始化之前设置,否则无效==。
     */
    public init(frame: CGRect, configuration: WKWebViewConfiguration)

    
    public init?(coder: NSCoder)

    
    /*! @abstract Navigates to a requested URL.
     @param request The request specifying the URL to which to navigate.
     @result A new navigation for the given request.
     @加载一个html网页根据一个URLRequest对象,返回一个WKNavigation对象,此对象暂时没有任何方法,属性。
 
     */
    open func load(_ request: URLRequest) -> WKNavigation?

    
    /*! @abstract Navigates to the requested file URL on the filesystem.
     @param URL The file URL to which to navigate.
     @param readAccessURL The URL to allow read access to.
     @discussion If readAccessURL references a single file, only that file may be loaded by WebKit.
     If readAccessURL references a directory, files inside that file may be loaded by WebKit.
     @result A new navigation for the given file URL.
     @加载本地html文件,url使用fileURL方法获取,readAccessURL为html文件所在的文件夹,的路径url,
     如果html用相对路径使用了本地js文件,最好使用此方法。
     
         示例:
      NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"webviewSdk"];
      NSString *htmlDic = [[NSBundle mainBundle] pathForResource:@"webviewSdk" ofType:@""];
      [self.wkWebview loadFileURL:[NSURL fileURLWithPath:htmlPath] allowingReadAccessToURL:[NSURL fileURLWithPath:htmlDic]];
      加载webviewSdk文件夹下的网页,webviewSdk文件要通过引用路径加载到项目中。
     */
    @available(iOS 9.0, *)
    open func loadFileURL(_ URL: URL, allowingReadAccessTo readAccessURL: URL) -> WKNavigation?

    
    /*! @abstract Sets the webpage contents and base URL.
     @param string The string to use as the contents of the webpage.
     @param baseURL A URL that is used to resolve relative URLs within the document.
     @result A new navigation.
     @加载html文件转化的字符串,baseURL用于解决html文件使用了相对路径来获取本地的js文件时需要传入。
     @baseUrl:加载的html所在的文件夹在项目中的路径。
     示例:
      NSString *mainBundlePath = [NSBundle mainBundle].bundlePath;
    NSString *basePath = [NSString stringWithFormat:@"%@/webviewSdk",mainBundlePath];
    NSURL *baseUrl = [NSURL fileURLWithPath:basePath isDirectory:YES];
    NSString *htmlPath1 = [NSString stringWithFormat:@"%@/index.html",basePath];
    NSString *htmlString2 = [NSString stringWithContentsOfFile:htmlPath1 encoding:NSUTF8StringEncoding error:NULL];
    [self.webview loadHTMLString:htmlString2 baseURL:baseUrl];
    加载webviewSdk文件夹下的html访问方式,在UIWebview中常用此方法加载本地html,WK中使用上面的allowingReadAccessTo方法更好。
     */
    open func loadHTMLString(_ string: String, baseURL: URL?) -> WKNavigation?

    
    /*! @abstract Sets the webpage contents and base URL.
     @param data The data to use as the contents of the webpage.
     @param MIMEType The MIME type of the data.
     @param encodingName The data's character encoding name.
     @param baseURL A URL that is used to resolve relative URLs within the document.
     @result A new navigation.
     NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyPage" ofType:@"html"];
    NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
    NSURL *baseURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
    [webView loadData:htmlData MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:baseURL.URLByDeletingLastPathComponent];
    }
     */
    @available(iOS 9.0, *)
    open func load(_ data: Data, mimeType MIMEType: String, characterEncodingName: String, baseURL: URL) -> WKNavigation?

    
    /*! @abstract Navigates to an item from the back-forward list and sets it
     as the current item.
     @param item The item to which to navigate. Must be one of the items in the
     web view's back-forward list.
     @result A new navigation to the requested item, or nil if it is already
     the current item or is not part of the web view's back-forward list.
     @seealso backForwardList
     @ wkWebview跳转到一个指定的WKBackForwardListItem,此time可以通过backForwardList来获取
     */
    open func go(to item: WKBackForwardListItem) -> WKNavigation?

    
    /*! @abstract The page title.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.
     @当前网页的title标签对应的值,此属性支持kvo观察模式
     */
    open var title: String? { get }

    
    /*! @abstract The active URL.
     @discussion This is the URL that should be reflected in the user
     interface.
     @link WKWebView @/link is key-value observing (KVO) compliant for this
     property.
     @获取wkwebview正在加载的url,此属性支持kvo观察模式
     */
    open var url: URL? { get }

    
    /*! @abstract A Boolean value indicating whether the view is currently
     loading content.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.
     @一个bool属性表示当前wkwebview是否正在加载内容
     */
    open var isLoading: Bool { get }

    
    /*! @abstract An estimate of what fraction of the current navigation has been completed.
     @discussion This value ranges from 0.0 to 1.0 based on the total number of
     bytes expected to be received, including the main document and all of its
     potential subresources. After a navigation completes, the value remains at 1.0
     until a new navigation starts, at which point it is reset to 0.0.
     @link WKWebView @/link is key-value observing (KVO) compliant for this
     property.
     @预估当前wkwebview加载的html的进度,可以通过kvo模式来实现一个加载进度条
     */
    open var estimatedProgress: Double { get }

    
    /*! @abstract A Boolean value indicating whether all resources on the page
     have been loaded over securely encrypted connections.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.
     @一个页面上的所有资源是否已经被安全加载
     */
    open var hasOnlySecureContent: Bool { get }

    
    /*! @abstract A SecTrustRef for the currently committed navigation.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant 
     for this property.
     */
    @available(iOS 10.0, *)
    open var serverTrust: SecTrust? { get }

    
    /*! @abstract A Boolean value indicating whether there is a back item in
     the back-forward list that can be navigated to.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.
     @seealso backForwardList.
     @是否可以后退
     */
    open var canGoBack: Bool { get }

    
    /*! @abstract A Boolean value indicating whether there is a forward item in
     the back-forward list that can be navigated to.
     @discussion @link WKWebView @/link is key-value observing (KVO) compliant
     for this property.
     @seealso backForwardList.
     @是否可以前进
     */
    open var canGoForward: Bool { get }

    
    /*! @abstract Navigates to the back item in the back-forward list.
     @result A new navigation to the requested item, or nil if there is no back
     item in the back-forward list.
     @后退
     */
    open func goBack() -> WKNavigation?

    
    /*! @abstract Navigates to the forward item in the back-forward list.
     @result A new navigation to the requested item, or nil if there is no
     forward item in the back-forward list.
     @前进
     */
    open func goForward() -> WKNavigation?

    
    /*! @abstract Reloads the current page.
     @result A new navigation representing the reload.
     @刷新wkwebview
     */
    open func reload() -> WKNavigation?

    
    /*! @abstract Reloads the current page, performing end-to-end revalidation
     using cache-validating conditionals if possible.
     @result A new navigation representing the reload.
     @重新加载当前页面,执行端到端重新验证,如果可能的话,使用缓存验证条件。
     */
    open func reloadFromOrigin() -> WKNavigation?

    
    /*! @abstract Stops loading all resources on the current page.
        @停止加载当前界面的所有资源文件
     */
    open func stopLoading()

    
    /* @abstract Evaluates the given JavaScript string.
     @param javaScriptString The JavaScript string to evaluate.
     @param completionHandler A block to invoke when script evaluation completes or fails.
     @discussion The completionHandler is passed the result of the script evaluation or an error.
     @执行js语句,并在执行完毕后返回block处理
    */
    open func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Swift.Void)? = nil)

    
    /*! @abstract Get a snapshot for the visible viewport of WKWebView.
     @param snapshotConfiguration An object that specifies how the snapshot is configured.
     @param completionHandler A block to invoke when the snapshot is ready.
     @discussion If the WKSnapshotConfiguration is nil, the method will snapshot the bounds of the 
     WKWebView and create an image that is the width of the bounds of the WKWebView and scaled to the 
     device scale. The completionHandler is passed the image of the viewport contents or an error.
     */
    
    @available(iOS 11.0, *)
    open func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?, completionHandler: @escaping (UIImage?, Error?) -> Swift.Void)

    
    /*! @abstract A Boolean value indicating whether horizontal swipe gestures
     will trigger back-forward list navigations.
     @discussion The default value is NO.
     @一个布尔值,指示是否水平滑动手势,会触发后向前列表导航吗
     */
    open var allowsBackForwardNavigationGestures: Bool

    
    /*! @abstract The custom user agent string or nil if no custom user agent string has been set.
        @如果没有设置自定义用户代理字符串,则自定义用户代理字符串或nil
    */
    @available(iOS 9.0, *)
    open var customUserAgent: String?

    
    /*! @abstract A Boolean value indicating whether link preview is allowed for any
     links inside this WKWebView.
     @discussion The default value is YES on Mac and iOS.
     @一个布尔值,指示是否允许任何链接预览,这个WKWebView中的链接
     */
    @available(iOS 9.0, *)
    open var allowsLinkPreview: Bool

    
    /*! @abstract The scroll view associated with the web view.
     */
    open var scrollView: UIScrollView { get }

    
    /* @abstract A Boolean value indicating whether magnify gestures will
     change the web view's magnification.
     @discussion It is possible to set the magnification property even if
     allowsMagnification is set to NO.
     The default value is NO.
     */
    
    /* @abstract The factor by which the page content is currently scaled.
     @discussion The default value is 1.0.
     */
    
    /* @abstract Scales the page content by a specified factor and centers the
     result on a specified point.
     * @param magnification The factor by which to scale the content.
     * @param point The point (in view space) on which to center magnification.
     */
    
    /* @abstract Checks whether or not WKWebViews handle the given URL scheme by default.
     @param scheme The URL scheme to check.
     */
    @available(iOS 11.0, *)
    open class func handlesURLScheme(_ urlScheme: String) -> Bool
}

WKWebViewConfiguration

/*! @abstract The process pool from which to obtain the view's web content
     process.
     @discussion When a web view is initialized, a new web content process
     will be created for it from the specified pool, or an existing process in
     that pool will be used.
     @WKProcessPool本类没有方法和属性
     当web视图初始化时,一个新的web内容进程
     将从指定的pool中为其创建,或者重用一个已存在pool中的进程。
     WKProcessPool 是个没有属性和方法的对象,唯一的作用就是标识是不是需要新的 session 级别的管理对象,一个实例代表一个对象
    */
    open var processPool: WKProcessPool

    
    /*! @abstract The preference settings to be used by the web view.
    @设置weibviw加载配置,例如最小字体,js是否可用,是否可以自动打开window
    */
    open var preferences: WKPreferences

    
    /*! @abstract The user content controller to associate with the web view.
    可以在加载web内容的时候添加用户指定的 js 脚本
    */
    open var userContentController: WKUserContentController

    
    /*! @abstract The website data store to be used by the web view.
    存储的 web 内容 cookies等
    WKWebsiteDataTypeCookies
    WKWebsiteDataTypeCookies
    WKWebsiteDataTypeDiskCache
    WKWebsiteDataTypeMemoryCache
    WKWebsiteDataTypeOfflineWebApplicationCache
    WKWebsiteDataTypeSessionStorage
    WKWebsiteDataTypeLocalStorage
    WKWebsiteDataTypeWebSQLDatabases
    WKWebsiteDataTypeIndexedDBDatabases

     */
    @available(iOS 9.0, *)
    open var websiteDataStore: WKWebsiteDataStore

    
    /*! @abstract A Boolean value indicating whether the web view suppresses
     content rendering until it is fully loaded into memory.
     @discussion The default value is NO.
     是否在所有的数据加载到内存中才开始渲染,默认为 NO
     */
    open var suppressesIncrementalRendering: Bool

    
    /*! @abstract The name of the application as used in the user agent string.
    设置应用的代理名称
    */
    @available(iOS 9.0, *)
    open var applicationNameForUserAgent: String?

    
    /*! @abstract A Boolean value indicating whether AirPlay is allowed.
     @discussion The default value is YES.
     */
    @available(iOS 9.0, *)
    open var allowsAirPlayForMediaPlayback: Bool

    
    @available(iOS 10.0, *)
    open var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes

    
    /*! @abstract A Boolean value indicating whether HTML5 videos play inline
     (YES) or use the native full-screen controller (NO).
     @discussion The default value is NO.
     */
    open var allowsInlineMediaPlayback: Bool

    
    /*! @abstract The level of granularity with which the user can interactively
     select content in the web view.
     @discussion Possible values are described in WKSelectionGranularity.
     The default value is WKSelectionGranularityDynamic.
     */
    open var selectionGranularity: WKSelectionGranularity

    
    /*! @abstract A Boolean value indicating whether HTML5 videos may play
     picture-in-picture.
     @discussion The default value is YES.
     */
    @available(iOS 9.0, *)
    open var allowsPictureInPictureMediaPlayback: Bool

    
    /*! @abstract An enum value indicating the type of data detection desired.
     @discussion The default value is WKDataDetectorTypeNone.
     An example of how this property may affect the content loaded in the WKWebView is that content like
     'Visit apple.com on July 4th or call 1 800 555-5545' will be transformed to add links around 'apple.com', 'July 4th' and '1 800 555-5545'
     if the dataDetectorTypes property is set to WKDataDetectorTypePhoneNumber | WKDataDetectorTypeLink | WKDataDetectorTypeCalendarEvent.
    
     */
    @available(iOS 10.0, *)
    open var dataDetectorTypes: WKDataDetectorTypes

    
    /*! @abstract A Boolean value indicating whether the WKWebView should always allow scaling of the web page, regardless of author intent.
     @discussion This will override the user-scalable property.
     The default value is NO.
     */
    @available(iOS 10.0, *)
    open var ignoresViewportScaleLimits: Bool

    
    /*! @abstract The directionality of user interface elements.
     @discussion Possible values are described in WKUserInterfaceDirectionPolicy.
     The default value is WKUserInterfaceDirectionPolicyContent.
     */
    
    /* @abstract Sets the URL scheme handler object for the given URL scheme.
     @param urlSchemeHandler The object to register.
     @param scheme The URL scheme the object will handle.
     @discussion Each URL scheme can only have one URL scheme handler object registered.
     An exception will be thrown if you try to register an object for a particular URL scheme more than once.
     URL schemes are case insensitive. e.g. "myprotocol" and "MyProtocol" are equivalent.
     Valid URL schemes must start with an ASCII letter and can only contain ASCII letters, numbers, the '+' character,
     the '-' character, and the '.' character.
     An exception will be thrown if you try to register a URL scheme handler for an invalid URL scheme.
     An exception will be thrown if you try to register a URL scheme handler for a URL scheme that WebKit handles internally.
     You can use +[WKWebView handlesURLScheme:] to check the availability of a given URL scheme.
     */
    @available(iOS 11.0, *)
    open func setURLSchemeHandler(_ urlSchemeHandler: WKURLSchemeHandler?, forURLScheme urlScheme: String)

    
    /* @abstract Returns the currently registered URL scheme handler object for the given URL scheme.
     @param scheme The URL scheme to lookup.
     */
    @available(iOS 11.0, *)
    open func urlSchemeHandler(forURLScheme urlScheme: String) -> WKURLSchemeHandler?

WKScriptMessageHandler

public protocol WKScriptMessageHandler : NSObjectProtocol {

    
    /*! @abstract Invoked when a script message is received from a webpage.
     @param userContentController The user content controller invoking the
     delegate method.
     @param message The script message received.
     通过userContentController注册的本地方法,在js端调用时会回调到此代理方法中,不能直接使用self左右代理对象会内存泄漏,应使用一个中间类来作为代理对象。
     */
    @available(iOS 8.0, *)
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
}

WKPreferences

@available(iOS 8.0, *)
open class WKPreferences : NSObject, NSSecureCoding {

    
    /*! @abstract The minimum font size in points.
     @discussion The default value is 0.
     @每个poit点对应的最小字体大小
     */
    open var minimumFontSize: CGFloat

    
    /*! @abstract A Boolean value indicating whether JavaScript is enabled.
     @discussion The default value is YES.
     @设置wkwebveiw的js是否可用
     */
    open var javaScriptEnabled: Bool

    
    /*! @abstract A Boolean value indicating whether JavaScript can open
     windows without user interaction.
     @discussion The default value is NO in iOS and YES in OS X.
     @一个布尔值,指示JavaScript是否可以打开没有用户交互的窗口
     */
    open var javaScriptCanOpenWindowsAutomatically: Bool

}

WKUserContentController

@available(iOS 8.0, *)
open class WKUserContentController : NSObject, NSSecureCoding {

    
    /*! @abstract The user scripts associated with this user content
     controller.
     @与此用户内容相关联的用户脚本控制器
    */
    open var userScripts: [WKUserScript] { get }

    
    /*! @abstract Adds a user script.
     @param userScript The user script to add.
    */
    open func addUserScript(_ userScript: WKUserScript)

    
    /*! @abstract Removes all associated user scripts.
    */
    open func removeAllUserScripts()

    
    /*! @abstract Adds a script message handler.
     @param scriptMessageHandler The message handler to add.
     @param name The name of the message handler.
     @discussion Adding a scriptMessageHandler adds a function
     window.webkit.messageHandlers..postMessage() for all
     frames.
     */
    open func add(_ scriptMessageHandler: WKScriptMessageHandler, name: String)

    
    /*! @abstract Removes a script message handler.
     @param name The name of the message handler to remove.
     */
    open func removeScriptMessageHandler(forName name: String)

    
    /*! @abstract Adds a content rule list.
     @param contentRuleList The content rule list to add.
     */
    @available(iOS 11.0, *)
    open func add(_ contentRuleList: WKContentRuleList)

    
    /*! @abstract Removes a content rule list.
     @param contentRuleList The content rule list to remove.
     */
    @available(iOS 11.0, *)
    open func remove(_ contentRuleList: WKContentRuleList)

    
    /*! @abstract Removes all associated content rule lists.
     */
    @available(iOS 11.0, *)
    open func removeAllContentRuleLists()
}

WKUserScript

@available(iOS 8.0, *)
public enum WKUserScriptInjectionTime : Int {

    
    case atDocumentStart

    case atDocumentEnd
}


/*! A @link WKUserScript @/link object represents a script that can be injected into webpages.
 */
@available(iOS 8.0, *)
open class WKUserScript : NSObject, NSCopying {

    
    /* @abstract The script source code. 
    */
    open var source: String { get }

    
    /* @abstract When the script should be injected. 
       @js啥时候注入
    */
    open var injectionTime: WKUserScriptInjectionTime { get }

    
    /* @abstract Whether the script should be injected into all frames or just the main frame. */
    open var isForMainFrameOnly: Bool { get }

    
    /*! @abstract Returns an initialized user script that can be added to a @link WKUserContentController @/link.
     @param source The script source.
     @param injectionTime When the script should be injected.
     @param forMainFrameOnly Whether the script should be injected into all frames or just the main frame.
     */
    public init(source: String, injectionTime: WKUserScriptInjectionTime, forMainFrameOnly: Bool)
}

WKScriptMessage

@available(iOS 8.0, *)
open class WKScriptMessage : NSObject {

    
    /*! @abstract The body of the message.
     @discussion Allowed types are NSNumber, NSString, NSDate, NSArray,
     NSDictionary, and NSNull.
     */
    open var body: Any { get }

    
    /*! @abstract The web view sending the message. */
    weak open var webView: WKWebView? { get }

    
    /*! @abstract The frame sending the message. */
    @NSCopying open var frameInfo: WKFrameInfo { get }

    
    /*! @abstract The name of the message handler to which the message is sent.
     */
    open var name: String { get }
}

WKWebsiteDataStore

iOS9以后才能用这个类,是代表webView不同的数据类型,cookies、disk、memory caches、WebSQL、IndexedDB数据库和本地存储。
@available(iOS 9.0, *)
open class WKWebsiteDataStore : NSObject, NSSecureCoding {

    
    /* @abstract Returns the default data store. 
        默认存储
*/
    open class func `default`() -> WKWebsiteDataStore

    
    /** @abstract Returns a new non-persistent data store.
     @discussion If a WKWebView is associated with a non-persistent data store, no data will
     be written to the file system. This is useful for implementing "private browsing" in a web view.
  暂时存储
    */
    open class func nonPersistent() -> WKWebsiteDataStore

    
    /*! @abstract Whether the data store is persistent or not. 
        是否是永久的存储
*/
    open var isPersistent: Bool { get }

    
    /*! @abstract Returns a set of all available website data types.
         所有的web存储类型
 */
    open class func allWebsiteDataTypes() -> Set

    
    /*! @abstract Fetches data records containing the given website data types.
      @param dataTypes The website data types to fetch records for.
      @param completionHandler A block to invoke when the data records have been fetched.
      根据网页的类型获取数据
    */
    open func fetchDataRecords(ofTypes dataTypes: Set, completionHandler: @escaping ([WKWebsiteDataRecord]) -> Swift.Void)

    
    /*! @abstract Removes website data of the given types for the given data records.
     @param dataTypes The website data types that should be removed.
     @param dataRecords The website data records to delete website data for.
     @param completionHandler A block to invoke when the website data for the records has been removed.
      根据网页的类型和时间删除数据
    */
    open func removeData(ofTypes dataTypes: Set, for dataRecords: [WKWebsiteDataRecord], completionHandler: @escaping () -> Swift.Void)

    
    /*! @abstract Removes all website data of the given types that has been modified since the given date.
     @param dataTypes The website data types that should be removed.
     @param date A date. All website data modified after this date will be removed.
     @param completionHandler A block to invoke when the website data has been removed.
     指定要删除的web的类型,这里指定的是所有的web的类型
    */
    open func removeData(ofTypes websiteDataTypes: Set, modifiedSince date: Date, completionHandler: @escaping () -> Swift.Void)

    
    /*! @abstract Returns the cookie store representing HTTP cookies in this website data store. 
    获取HttpCookie
*/
    @available(iOS 11.0, *)
    open var httpCookieStore: WKHTTPCookieStore { get }
}

WKContentRuleList和WKScriptMessageHandler

WKWebView中新增了一个功能,可以对WebView的内容添加一些自定义的过滤规则。这个功能原来在 Safari Extension 中被引入,从 11 开始同样适用于WKWebView。

[https://www.jianshu.com/p/8af24e9dc82e](https://note.youdao.com/)
@available(iOS 11.0, *)
open class WKContentRuleList : NSObject {

    
    /*! @abstract A copy of the identifier of the content extension. */
    open var identifier: String! { get }
}




public protocol WKScriptMessageHandler : NSObjectProtocol {

    
    /*! @abstract Invoked when a script message is received from a webpage.
     @param userContentController The user content controller invoking the
     delegate method.
     @param message The script message received.
     @从网页接收到脚本消息时调用
     */
    @available(iOS 8.0, *)
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
}

Delegate

 /*! @abstract Decides whether to allow or cancel a navigation.
     @param webView The web view invoking the delegate method.
     @param navigationAction Descriptive information about the action
     triggering the navigation request.
     @param decisionHandler The decision handler to call to allow or cancel the
     navigation. The argument is one of the constants of the enumerated type WKNavigationActionPolicy.
     @discussion If you do not implement this method, the web view will load the request or, if appropriate, forward it to another application.
     @available(iOS 8.0, *)
     是否允许开始一个请求导航,webview开始加载调用的第一个方法
     decisionHandler 不能回调多次
     */
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void){
        let url = navigationAction.request.url?.absoluteString;
        if url?.range(of: "qu.la") != nil && url?.range(of: "jsa") == nil{
            decisionHandler(.allow)
            return;
        }
        print(navigationAction.request.url?.absoluteString ?? "没有url")
        decisionHandler(.cancel)
    }
    
    
    /*! @abstract Decides whether to allow or cancel a navigation after its
     response is known.
     @param webView The web view invoking the delegate method.
     @param navigationResponse Descriptive information about the navigation
     response.
     @param decisionHandler The decision handler to call to allow or cancel the
     navigation. The argument is one of the constants of the enumerated type WKNavigationResponsePolicy.
     @discussion If you do not implement this method, the web view will allow the response, if the web view can show it.
     @available(iOS 8.0, *)
     请求收到响应以后是否允许继续加载
     */
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Swift.Void){
        decisionHandler(.allow)
    }
    
    
    /*! @abstract Invoked when a main frame navigation starts.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @available(iOS 8.0, *)
     开始加载网页
     */
    
     func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!){
    }
    
    
    /*! @abstract Invoked when a server redirect is received for the main
     frame.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @available(iOS 8.0, *)
     请求重定向到其他服务器
     */
    
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!){
    }
    
    
    /*! @abstract Invoked when an error occurs while starting to load data for
     the main frame.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @param error The error that occurred.
     @available(iOS 8.0, *)
     在加载网页资源过程中发生错误或取消加载都会调用此方法
     */
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error){
        print("网页加载失败")
    }
    
    
    /*! @abstract Invoked when content starts arriving for the main frame.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @available(iOS 8.0, *)
     开始接受网页内容
     */
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
    }
    
    
    /*! @abstract Invoked when a main frame navigation completes.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @available(iOS 8.0, *)
     请求结束
     */
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
    }
    
    
    /*! @abstract Invoked when an error occurs during a committed main frame
     navigation.
     @param webView The web view invoking the delegate method.
     @param navigation The navigation.
     @param error The error that occurred.
     @available(iOS 8.0, *)
     接受网页内容是发生偶然错误,会调用,不会打断接受网页内容。
     */
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
        print("接受网页内容是发生错误")
    }
    
    
    /*! @abstract Invoked when the web view needs to respond to an authentication challenge.
     @param webView The web view that received the authentication challenge.
     @param challenge The authentication challenge.
     @param completionHandler The completion handler you must invoke to respond to the challenge. The
     disposition argument is one of the constants of the enumerated type
     NSURLSessionAuthChallengeDisposition. When disposition is NSURLSessionAuthChallengeUseCredential,
     the credential argument is the credential to use, or nil to indicate continuing without a
     credential.
     @discussion If you do not implement this method, the web view will respond to the authentication challenge with the NSURLSessionAuthChallengeRejectProtectionSpace disposition.
     @available(iOS 8.0, *)
     https请求时的挑战验证
     */
    
     func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){
        print("999999")
        completionHandler(.cancelAuthenticationChallenge, nil)
    }
    
    
    /*! @abstract Invoked when the web view's web content process is terminated.
     @param webView The web view whose underlying web content process was terminated.
     @available(iOS 9.0, *)
     WKWebview的加载UI都是otherProcess其他进程中完成的,如果在其他进程中出现错误会导致白屏,
     这个代理方法能够监听白屏的通知,当在其他进程中白屏后就会调用这个代理。
     */
    
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView){
    }

你可能感兴趣的:(WKWebview详解一,基础API)