加载css不能100%工作怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (83)

以下是代码:

// ==UserScript==
// @name    _Style iframe with src="about:blank"
// @match   https://mail.google.com/tasks/canvas
// ==/UserScript==

var targetFrame = document.querySelector("iframe[src='about:blank']");

  if (targetFrame) {
    addStyleToFrame(
      `* {color: red !important}`, targetFrame
    );


    function addStyleToFrame(cssStr, frmNode) {
      var D = frmNode.contentDocument;
      var newNode = D.createElement('style');
      newNode.textContent = cssStr;

      var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
      targ.appendChild(newNode);
    }
  }

// ==UserScript==
// @name    _Style iframe with src="about:blank"
// @match   https://mail.google.com/tasks/canvas
// ==/UserScript==

var targetFrame = document.querySelector("iframe[src='about:blank']");
document.querySelector("iframe[src='about:blank']").onload = function() {
  if (targetFrame) {
    addStyleToFrame(
      `* {color: red !important}`, targetFrame
    );


    function addStyleToFrame(cssStr, frmNode) {
      var D = frmNode.contentDocument;
      var newNode = D.createElement('style');
      newNode.textContent = cssStr;

      var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
      targ.appendChild(newNode);
    }
  }}
提问于
用户回答回答于

通过这样的修改解决 :

// ==UserScript==
// @name     _Style iframe with src="about:blank"
// @match    https://mail.google.com/tasks/canvas
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

const desiredStyles = `* {color: red !important;}`;

waitForKeyElements (
    ".goog-toolbar:first",
    addCSS_Style,
    false,
    "iframe[src='about:blank']"
);

function addCSS_Style (jNode) {
    var frmBody = jNode.closest ("body");
    //-- Optionally add a check here to avoid duplicate <style> nodes.
    frmBody.append (`<style>${desiredStyles}</style>`);
}

// ==UserScript==
// @name     tasks
// @match    https://mail.google.com/tasks/canvas
// @run-at   document-start
// ==/UserScript==

const css = `
  * {color: red !important}
`;

addStyle(css);

new MutationObserver((_, observer) => {
  const iframe = document.getElementsByTagName('iframe')[0];
  if (iframe) {
    observer.disconnect();
    iframe.addEventListener('load', () => addStyle(css, iframe), {once: true});
  }
}).observe(document, {subtree: true, childList: true});

function addStyle(css, frame = window) {
  const doc = frame.contentDocument || frame.document;
  const el = document.createElement('style');
  el.textContent = css;
  doc.documentElement.appendChild(el);
}

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动