2010-04-15 21 views
1

我正在嘗試編寫一個Ubiquity命令,允許您使用該圖像本身替換指向圖像的選定鏈接或URL。然而,CmdUtils.setSelection()函數(記錄here)似乎什麼都不做,如果有任何html標籤出現在選擇中,使其無法替換任何鏈接。選擇純文本時,其功能與預期完全相同,用<img src="text"/>標籤代替文本。有什麼我失蹤了,或者這個功能會不會允許我替換HTML?如果後者是這種情況,是否有一種功能或方法可以讓我做到這一點?任何其他建議也歡迎!Ubiquity CmdUtils.setSelection將不會取代HTML

CmdUtils.CreateCommand({ 
    name: "fetch-image", 
    author: {name: "Josh Timmer"}, 
    license: "GPL", 
    description: "Replaces links or URLs pointing to images with the image itself", 
    help: "Highlight text or a hyperlink and execute this command", 
    takes: {"image URL": /.*/}, 

    _getImgUrl: function(itemIq) { 
    if (itemIq.html.indexOf("<a ",0) < 0) 
     return itemIq.text; 
    var refPos = itemIq.html.indexOf("href=\"",0); 
    if (refPos < 0) 
     return "Error, no URL found!"; 
    var startPos = itemIq.html.indexOf("\"", refPos); 
    var endPos = itemIq.html.indexOf("\"", startPos + 1); 
    startPos += 1; 
    var url = itemIq.html.substring(startPos, endPos); 
    return url; 
    }, 

    preview: function(pblock, input) { 
    pblock.innerHTML = "Image URL: " + this._getImgUrl(input) + "<br/><br/><img src='" + this._getImgUrl(input) + "'/>"; 
    }, 

    execute: function img_insert(input) { 
    CmdUtils.setSelection("<img src='" + this._getImgUrl(input) + "'/>"); 
    displayMessage("Executed: " + this._getImgUrl(input)); 
    } 
}); 

回答

1

只要傳遞有效的HTML,它就應該可以工作。

CmdUtils.CreateCommand({ 
    name: "fetch image", 
    authors: [{name: "Josh Timmer"}, "satyr"], 
    license: "GPL", 
    description: "Replaces links pointing to images with the image itself.", 
    help: "Highlight text or a hyperlink and execute this command.", 
    preview: function fetch_image_preview(pblock) { 
    pblock.innerHTML = this._images() || this.previewDefault(); 
    }, 
    execute: function fetch_image_execute() { 
    CmdUtils.selection = this._images(); 
    }, 
    _images: function fetch_image_urls(){ 
    var srcs = CmdUtils.getSelectedNodes("a"); 
    if (!srcs.length) srcs = CmdUtils.selection.match(/\bhttps?:\/+\S+/g); 
    return [<img src={s}/>.toXMLString() for each (s in srcs)].join(""); 
    }, 
});