虽然谷歌浏览器现在定义unsafeWindow
了用户脚本,但它不允许对目标页面的 javascript 对象进行任何访问。它只允许访问 DOM。
要解决此问题,您可以为脚本提供一个跨浏览器、功能齐全的脚本unsafeWindow
——如本答案所示:
/*--- Create a proper unsafeWindow object on browsers where it doesn't exist
(Chrome, mainly).
Chrome now defines unsafeWindow, but does not give it the same access to
a page's javascript that a properly unsafe, unsafeWindow has.
This code remedies that.
*/
var bGreasemonkeyServiceDefined = false;
try {
if (typeof Components.interfaces.gmIGreasemonkeyService === "object") {
bGreasemonkeyServiceDefined = true;
}
}
catch (err) {
//Ignore.
}
if ( typeof unsafeWindow === "undefined" || ! bGreasemonkeyServiceDefined) {
unsafeWindow = ( function () {
var dummyElem = document.createElement('p');
dummyElem.setAttribute ('onclick', 'return window;');
return dummyElem.onclick ();
} ) ();
}
或者,您可以重构脚本以使用脚本注入...
function main () {
//--- PUT EVERYTHING IN THIS WRAPPER FUNCTION...
var tm = tinyMCE;
if (tm!= null) {
var _tempcontent = tm.activeEditor.getContent();
console.log(_tempcontent);
}
}
addJS_Node (null, null, main);
function addJS_Node (text, s_URL, funcToRun) {
var D = document;
var scriptNode = D.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
//--- Don't error check here. if DOM not available, should throw error.
targ.appendChild (scriptNode);
}