我从this question得到了下面的代码,这个脚本是用来在带有Chrome扩展的Google tasks上的iframe[src="about:blank"]
中改变CSS。
// ==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);
}
}
这段代码有时会将字体颜色改为红色,但有时却不会,如何让这段代码100%地工作?
图2.修改了第一个代码以等待加载,但仍然不稳定,就像这样(我只是用下面的第二个代码按F5
和shift + F5
来刷新页面。)
// ==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);
}
}}
发布于 2018-08-12 04:56:24
通过像这样修改来解决。我感到非常羞愧,以至于我不得不每次都不断地询问可能是最基本的技能。第一个代码是由Brock Adams post在here上从下到上编写的。
答案1.添加等待密钥Element.js
// ==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>`);
}
答案2.使用wOxxOm on forum.userstyles.org提供的突变观察者
// ==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);
}
https://stackoverflow.com/questions/51798363
复制相似问题