最近做浏览器项目,要求添加一个类似UC浏览器,QQ浏览器的夜间模式,通过各种差,终于发现一种可以管用的办法.
目前还不完善,只是简单的实现了功能,还要继续探索,因为只能在加载完网页之后才能调用,所以会有明显的闪动,找到办法后会继续更新记录.
网页加载完成后,通过代理方法func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
,在其中添加以下代码即可实现网页的夜间模式
webView.evaluateJavaScript("javascript:(function(){var styleElem=null,doc=document,ie=doc.all,fontColor=50,sel='body,body *';styleElem=createCSS(sel,setStyle(fontColor),styleElem);function setStyle(fontColor){var colorArr=[fontColor,fontColor,fontColor];return'background-color:#000 !important;color:RGB('+colorArr.join('%,')+'%) !important;'};function createCSS(sel,decl,styleElem){var doc=document,h=doc.getElementsByTagName('head')[0],styleElem=styleElem;if(!styleElem){s=doc.createElement('style');s.setAttribute('type','text/css');styleElem=ie?doc.styleSheets[doc.styleSheets.length-1]:h.appendChild(s)};if(ie){styleElem.addRule(sel,decl)}else{styleElem.innerHTML='';styleElem.appendChild(doc.createTextNode(sel+' {'+decl+'}'))};return styleElem}})();", completionHandler: nil)
js代码:
javascript: (function() {
var styleElem = null,
doc = document,
ie = doc.all,
fontColor = 50,
sel = 'body,body *';
styleElem = createCSS(sel, setStyle(fontColor), styleElem);
function setStyle(fontColor) {
var colorArr = [fontColor, fontColor, fontColor];
return 'background-color:#000 !important;color:RGB(' + colorArr.join('%,') + '%) !important;'
};
function createCSS(sel, decl, styleElem) {
var doc = document, h = doc.getElementsByTagName('head')[0], styleElem = styleElem;
if (!styleElem) {
s = doc.createElement('style');
s.setAttribute('type', 'text/css');
styleElem = ie ? doc.styleSheets[doc.styleSheets.length - 1] : h.appendChild(s)
};
if (ie) {
styleElem.addRule(sel, decl)
} else {
styleElem.innerHTML = '';
styleElem.appendChild(doc.createTextNode(sel + ' {' + decl + '}'))
};
return styleElem
};
})();
网友评论