Search code examples
javascriptimagefirefox-addoncreateelement

Image created via Javascript not displayed


I'm writing a extension for Firefox that adds images to the current web page. Although it shouldn't be a problem, the following code snippet doesn't work. I got a 50px/50px rectangle, i.e., the border of the image, but the image itself is not displayed.

var img = document.createElement("img");
img.style.border = "1px solid #000";
img.style.width = "50px";
img.style.height = "50px";
img.setAttribute("src", "chrome://myExtension/content/images/add-icon.png");

It also doesn't work with images from a external results. Adding div-environments seem to work. img.src="..." doesn't change anything.

I try to add the image to a div. After adding div.length has increased by 1. So somehow everything is working, except the image is not displayed. Any hints?

Thanks and best regards,

Christian


Solution

  • var body = content.document.getElementsByTagName("BODY").item(0);
    var img = document.createElement("img");
    img.src = "chrome://myExtension/content/images/add-icon.png";
    var divBox = document.createElement("div");
    divBox.appendChild(img);
    body.appendChild(divBox); 
    

    As discussed in comments, use "content.document" consistently, instead of mixing "content.document" and "document".