1

我的问题是尝试使用用户脚本获取 Tumblr 的 tinymce 编辑器的内容。在 Firefox 中,这非常有效:

var tm = (unsafeWindow.tinyMCE) ? unsafeWindow.tinyMCE : null;  
if(tm!= null){
    var _tempcontent = tm.activeEditor.getContent();
    console.log(_tempcontent);
}

但是在 Chrome 中我得到“未定义”,然后当我修改 unsafeWindow 时,我找不到 tinymce 实例,而在 Firefox 中存在。

4

1 回答 1

1

虽然谷歌浏览器现在定义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);
}
于 2012-06-08T08:19:04.063 回答