我正在尝试编写一个Ubiquity命令,允许您用该图像本身替换指向图像的选定链接或URL。但是,如果选择中存在任何html标记,则CmdUtils.setSelection()函数(记录为here)似乎无效,这使得替换任何链接无效。选择纯文本时,它的功能与预期完全相同,用<img src="text"/>
标记替换文本。有什么我缺少的,或者这个功能根本不允许我替换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));
}
});
答案 0 :(得分: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("");
},
});