美文网首页
iOS webview夜间模式

iOS webview夜间模式

作者: 糊涂糊涂啊 | 来源:发表于2018-01-25 15:01 被阅读425次

    最近做浏览器项目,要求添加一个类似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
      };
    })();

    相关文章

      网友评论

          本文标题:iOS webview夜间模式

          本文链接:https://www.haomeiwen.com/subject/xluvaxtx.html