OC 修改js方法实现详析
2019-12-18 本文已影响0人
年轻就要活出样
注意以下枚举
/*! @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代码
<input type="button" value="重定义系统方法" onclick="locationClick()" /> 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代码
<input type="button" value="注入JS未实现方法" onclick="shareClick()" />
- OC代码注入 注意:这里使用
WKUserScriptInjectionTimeAtDocumentEnd
或injectionTime: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代码
<input type="button" value="重定义JS方法实现" onclick="colorClick()" /> 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]];