注意以下枚舉
/*! @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系統(tǒng)方法實(shí)現(xiàn)(alert為例)
- 例1:
<input type="button" value="重定義系統(tǒng)方法" onclick="locationClick()" />
function locationClick() {
alert('4444')
}
// 以下兩種注入方式都可以
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未實(shí)現(xiàn)方法(alert為例)
- 例1馒吴、
<input type="button" value="注入JS未實(shí)現(xiàn)方法" 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方法的原有實(shí)現(xiàn)
- 例1稠茂、
<input type="button" value="重定義JS方法實(shí)現(xiàn)" 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]];