在火狐附加组件面板中显示远程图像

Displaying remote images in a firefox add-on panel

本文关键字:程图像 图像 显示 火狐 组件      更新时间:2023-09-26

我正在尝试在FireFox附加面板中显示远程图像,但是src属性正在从如下所示的内容转换:

http://example.com/image.jpg

像这样:

resource://addon_name/data/%22http://example.com/image.jpg%22

无法确定我是否违反了安全策略。

在我的附加脚本(index.js)中,我使用 sdk/request API 检索图像 URL,并将它们传递给我的内容脚本(data/my-panel.js)。我的 data/my-panel.js 文件正在使用从 index.js 传递的 URL 在我的面板文件 (data/popup.html) 中创建 DOM 元素(包括图像)。以下是相关的代码位:

index.js

var Request = require("sdk/request").Request;
var panel = require("sdk/panel").Panel({
  width: 500,
  height: 500,
  contentURL: "./popup.html",
  contentScriptFile: "./my-panel.js"
});
  Request({
      url: url,
      onComplete: function(response) {
           // Get the JSON data.
          json = response.json;
          // Launch the popup/panel.
          panel.show();
          panel.port.emit("sendJSON", json);
      }
  }).get();

data/my-panel.js

var title;
var desc;
var list;
var titleTextNode;   
var descTextNode; 
self.port.on("sendJSON", function(json) {
    json.docs.forEach(function(items) {
        title = JSON.stringify(items.sourceResource.title);
        desc = JSON.stringify(items.sourceResource.description);
        img = JSON.stringify(items.object);       
        console.log(img);
        var node = document.createElement("li");                 // Create a <li> node
        var imgTag = document.createElement("img");                 // Create a <img> node
        imgTag.setAttribute('src', img);
        imgTag.setAttribute('alt', desc);
        imgTag.style.width= '25px';
        titleTextNode = document.createTextNode(title);
        descTextNode = document.createTextNode(desc);
        node.appendChild(titleTextNode);                         // Append the text to <li>
        node.appendChild(descTextNode);                          // Append the text to <li>
        document.getElementById("myList").appendChild(node);     // Append <li> to <ul> with id="myList"
        document.getElementById("myImgs").appendChild(imgTag);
    });
});

console.log(img)行正确显示 URL,但不在弹出窗口中显示.html...

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <ul id="myList"></ul>
    <p id="myImgs"></p>
</body>
</html>

如何使图像的src属性直接指向远程 URL?谢谢!

我发现我做错了什么。在 img URL 上使用 JSON.stringify() 在其周围添加了双引号。删除它修复了图像:

img = items.object;

我不太确定 SDK 权限,但作为最后的手段,您可以将远程 url 转换为资源 URI,如下所示 -

var res = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
res.setSubstitution("rawr", Services.io.newURI('http://www.bing.com/',null,null));
// now try navigating to resource://rawr it will load bing

然后你可以加载resource://rawr它应该可以工作。