在Chrome上更改具有src =“ about:blank”的iframe内容的CSS

时间:2018-08-11 01:59:39

标签: javascript css iframe tampermonkey

我正在尝试使用此代码在the Google Tasks pagethe extension Tampermonkey上应用新设计。

当我尝试html{ display: none !important }时,由于html标签不在iframe下,它什么也不显示。 但是,我无法在iframe[src="about:blank"]元素下进行修改。 我应该如何修改才能使其正常工作?


快照1 .:不适用于iframe[src="about:blank"]

内部
// ==UserScript==
// @name     test
// @match    https://mail.google.com/tasks/canvas
// @match    about:blank
// @grant    GM_addStyle
// ==/UserScript==

GM_addStyle ( `    
* {color: red !important}
` );

1 个答案:

答案 0 :(得分:1)

是的,使用src="about:blank"为iframe编写脚本可能很棘手,因为普通的用户脚本机制无法正常工作。 (当前@match about:blank does not work,但是无论如何在这里使用它都是一个坏主意,因为它会产生全局副作用。)

幸运的是,在Chrome上,运行Tampermonkey脚本时,带有src="about:blank"的iframe几乎总是有一个documentElement,因此如果您只是添加CSS < / strong>。

这是一个完整的工作脚本,其样式类似于第一个iframe:

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

//-- Adjust the following selector to match your page's particulars, if needed.
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);
}



如果<iframe>标签是用javascript创建的,或者其他延迟阻碍了上述操作...

使用the iframeSelector parameter of waitForKeyElements解决此问题。

诀窍是选择一个始终出现在完成的iframe中的节点,并将其传递给waitForKeyElements。
该节点应该是唯一的。
但是对于以下示例,我使用.goog-toolbar:first作为快速的第一次尝试。

这是完整的工作脚本

// ==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>`);
}



注意:

  1. GM_addStyle()在这种情况下不起作用,因此我们添加了具有框架感知功能的样式。
  2. Google页面使用:多个嵌套的iframe;复杂页面(重新)处理;和HTML的“信息气味”较差。简而言之,它们是邪恶的,千变万化的,可能很难为它们编写脚本。因此,这个简单的示例将起作用,但这仅是该问题的范围。对于更复杂的情况,请提出一个新问题,并准备大量啤酒。