OC 修改js方法实现详析

注意以下枚举

/*! @enum WKUserScriptInjectionTime
 @abstract when a user script should be injected into a webpage.
 @constant WKUserScriptInjectionTimeAtDocumentStart    Inject the script after the document element has been created, but before any other content has been loaded.
 @constant WKUserScriptInjectionTimeAtDocumentEnd      Inject the script after the document has finished loading, but before any subresources may have finished loading.
 */
NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSInteger, WKUserScriptInjectionTime) {
    WKUserScriptInjectionTimeAtDocumentStart,
    WKUserScriptInjectionTimeAtDocumentEnd
} API_AVAILABLE(macos(10.10), ios(8.0));

修改js系统方法实现(alert为例)

  • 例1:
    • js代码
            
            function locationClick() {
                 alert('4444')
             }
    
    • OC代码注入
     // 以下两种注入方式都可以
     NSString *jsCode = @"alert = (function (oriAlertFunc){ \
                           return function(task)\
                           {\
                            window.webkit.messageHandlers.ocZRAction.postMessage(task);\
                             oriAlertFunc.call(alert,task);\
                           }\
                           })(alert);";
     NSString *jsCode3 = @"alert =  function(task)\
        {\
         window.webkit.messageHandlers.asyncAction.postMessage(task);\
        }";
     [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
    
    

注入JS未实现方法(alert为例)

  • 例1、
    • JS代码
            
    
    • OC代码注入 注意:这里使用WKUserScriptInjectionTimeAtDocumentEndinjectionTime:WKUserScriptInjectionTimeAtDocumentStart都可以
        NSString *jsCode6 = @"shareClick =  function(task)\
               {\
                window.webkit.messageHandlers.GoBack.postMessage(task);\
               }";
      [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode6 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]];
      [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode6 injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
    

修改JS方法的原有实现

  • 例1、
    • JS代码
         
        function colorClick() {
                  alert('55555')
             }
    
    • OC代码
      注意:这里使用WKUserScriptInjectionTimeAtDocumentEnd不能用WKUserScriptInjectionTimeAtDocumentStart
      NSString *jsCode7 = @"colorClick =  function(task)\
                  {\
                   window.webkit.messageHandlers.GoBack.postMessage(task);\
                  }";
       [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode7 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]];
    
    

你可能感兴趣的:(OC 修改js方法实现详析)