WKWebView中注入CSS

  • 因为css要添加到head中, 因此注入的时机应该是WKUserScriptInjectionTimeAtDocumentEnd,否则找不到head会注入失败。

  • iOS代码

NSStringEncoding enc = NSUTF8StringEncoding;
NSString *scriptString = [NSString stringWithContentsOfFile:@"jsPath.js" usedEncoding:&enc error:nil];
WKUserScript *script =
[[WKUserScript alloc] initWithSource: scriptString
                           injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
                        forMainFrameOnly:YES];
[webView.configuration.userContentController addUserScript: script];
  • js代码
function addNewStyle(newStyle) {
    var styleElement = document.getElementById('lxg_styles_js');
    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.innerHTML = newStyle;
        styleElement.id = 'lxg_styles_js';
        document.head.appendChild(styleElement);
  }
}
window.onload = addNewStyle("img[src*=\"hiddenImgSrc\"]{display: none;}");

你可能感兴趣的:(WKWebView中注入CSS)