我正在尝试使用此代码在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}
` );
答案 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>`);
}
注意:
GM_addStyle()
在这种情况下不起作用,因此我们添加了具有框架感知功能的样式。