美文网首页
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夜间模式

    最近做浏览器项目,要求添加一个类似UC浏览器,QQ浏览器的夜间模式,通过各种差,终于发现一种可以管用的办法.目前还...

  • iOS13-适配夜间模式/深色外观(Dark Mode)

    iOS13-适配夜间模式/深色外观(Dark Mode) iOS13-适配夜间模式/深色外观(Dark Mode)

  • iOS关于换肤和夜间模式的一些思考

    iOS关于换肤和夜间模式的一些思考 iOS关于换肤和夜间模式的一些思考

  • iOS swift 夜间模式实现

    夜间模式 iOS 13 以上 @available(iOS 13.0, *) staticletlightGr...

  • WebView重置夜间模式问题

    最近一个项目中使用了DayNight 主题来实现换肤效果。大概就是创建一个新的values-night把再新建一个...

  • ios 夜间模式

    1、真对我们的项目来说 夜间模式是后来项目完工的时候增加的需求, 所以后来直接用这种方式,简单粗暴,直接改wind...

  • iOS 夜间模式

    先来看看效果图 思路 切换夜间/白天模式时,发送通知给所有ViewController,让它们切换到相应的主题。但...

  • iOS 换肤方案

    iOS换肤需求 1、由于iOS13发布的夜间模式,市场上较大型的APP都以积极的适配了夜间模式,因此我们的APP也...

  • iOS webview 通过注入css文件实现夜间模式

    最近项目需要实现夜间模式,因为是老项目,所以原生的界面找了个优秀的第三方库DKNightVersion ,对于老项...

  • iOS-夜间模式(换肤设置)

    iOS 开发中有时候会有夜间模式(换肤设置)的需求, 其实主要是更改相关颜色操作! 思路:每次切换夜间/白天模式...

网友评论

      本文标题:iOS webview夜间模式

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