是的,为 iframe 编写脚本src="about:blank"
可能会很棘手,因为正常的用户脚本机制的工作方式不同。 (现在, @match about:blank不起作用 https://github.com/Tampermonkey/tampermonkey/issues/312,但无论如何在这里使用它都是一个坏主意,因为它会产生全局副作用。)
幸运的是,在 Chrome 上,iframe 具有src="about:blank"
几乎总是有一个documentElement
当 Tampermonkey 脚本运行时,因此您通常不需要等待只需添加 CSS.
Here is 一个完整的工作脚本,第一个 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);
}
If the <iframe>
标签是由 javascript 创建的,或者其他延迟妨碍了上述操作...
Use the iframeSelector的参数waitForKeyElements https://gist.github.com/BrockA/2625891解决这个问题。
技巧是选择一个始终出现在完成的 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>`);
}
Notes:
-
GM_addStyle()
在这种情况下不起作用,因此我们添加具有框架感知功能的样式。
- Google 页面使用:多个嵌套的 iframe;复杂的页面(重新)修改; HTML 的“信息气味”很差。简而言之,它们是邪恶的、不断变化的,并且编写脚本可能会很痛苦。因此,这个简单的示例将起作用,但这就是这个问题范围内的全部内容。对于更复杂的场景,提出一个新问题并手头上有足够的啤酒钱。