【问题标题】:Getting content from tinyMCE with userscripts in Chrome在 Chrome 中使用用户脚本从 tinyMCE 获取内容
【发布时间】:2012-06-08 16:19:04
【问题描述】:

我的问题是尝试使用用户脚本获取 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 中存在。

【问题讨论】:

  • 什么是未定义的?变量 tm?你能检查一下var tinymce吗?你得到了什么?
  • 是的,变量 tm 是未定义的,因为 unsafeWindow.tinyMCE 也不是。

标签: google-chrome tinymce greasemonkey userscripts


【解决方案1】:

虽然 Google Chrome 现在为用户脚本定义了unsafeWindow,但it does not allow any access to the target page's javascript objects。它只允许访问 DOM。

要解决此问题,您可以为脚本提供跨浏览器、功能齐全的unsafeWindow -- 如this answer 所示:

/*--- 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);
}

【讨论】:

  • 这两个选项似乎适用于我在互联网上找到的一些 tintmce 演示,因为我在工作,代理设置现在不允许我进入 tumblr 我将在我测试时进行测试回家。谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多