gpt4 book ai didi

javascript - 在 Chrome 上更改具有 src ="about:blank"的 iframe 内容的 CSS

转载 作者:行者123 更新时间:2023-11-29 23:18:21 26 4
gpt4 key购买 nike

我正在尝试使用此代码在 the Google Tasks page 上应用新设计与 the 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}
` );

最佳答案

是的,使用 src="about:blank" 为 iframe 编写脚本可能会很棘手,因为正常的用户脚 native 制无法正常工作。 (目前 @match about:blank does not work,但在这里使用它并不是一个好主意,因为它会产生全局副作用。)

幸运的是,在 Chrome 上,带有 src="about:blank" 的 iframe几乎总是有一个documentElement到 Tampermonkey 脚本运行时,因此如果您只是添加 CSS,通常不需要等待。

这是一个完整的工作脚本,它为第一个 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。简而言之,它们是邪恶的、不断变化的,而且编写脚本可能会很痛苦。所以,这个简单的例子会起作用,但这就是这个问题的范围。对于更复杂的场景,打开一个新问题,手头有足够的啤酒钱。

关于javascript - 在 Chrome 上更改具有 src ="about:blank"的 iframe 内容的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51795821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com