Saturday, January 14, 2012

Firefox extension programming: insert an image to the document


The Firefox extension can insert things to the document you are viewing. This document (or web page) is not the one the Firefox extension is referring as the *document* element. To access it, one of the methods is to use:

      var doc = getBrowser().contentWindow.document;

Now *doc* is the document object of the current page in the content window.

To insert a paragraph to the bottom of the current page, you can simply do:

      var p = doc.createElement('p');
      p.textContent = 'Hello world!';
      doc.body.appendChild(p);

Now back to the topic. If I want to insert an image into the current page, how should I do it? Supposed the image is stored as chrome://myextension/skin/myimg.png, will this work?

      var img = doc.createElement('img');
      img.src = 'chrome://myextension/skin/myimg.png';
      doc.body.appendChild(img);

That would not work. The content document has no access to that image in the local disk.

To make it work, you may put the image on the internet so img.src can point to it. Or you can use an *iframe* to embed chrome://myextension/skin/myimg.png (I haven't tried this but I think it should work.) If the image is not big -- e.g. an icon, here is a more interesting way to do it:

1) Calculate the Base64 encoding of the imge file. If you are using Linux, that is easy, just run:

      $ base64 myimg.png

2) Set the img.src as data type with the output Base64 encoding of the image file.

      img.src = 'data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAA3XAAAN1wFCKJt4AAAAB3RJTUUH1QsKEAYBqzHCKQAAAxFJREFUOMvVlU+IHEUUh7/q6prent6dzc5mFxcUMQZEI4qI6EESwYsHzdGjomchRwmYDZJcPCt4WYIHg+QUTIgg63V1RSNuFmOMJuqazIQ9ZDM7f3u7qp6H6WlnMmiU5GJDUd393vv61e9VvYb/26WWTiy9CyzeY+6xEFg8+PJBsdaqf/IUEf6N3RjD2XNnj4QAzjn1wUdn+HbtZwZ0Afq+gnhBkMIgInikuBcEEXh07wMcfutVAEIApRQr3/zInieeJwgCjHbEseNmQ2OdxzqPcx4A6wTrHNb6EZu1nvXLF1FK/QUGCLWiOp1w/30prxyYpFqp8tnKVb5eSwpAH5yD3G1g52k2dSFNAQ6CgKkk4pl9KXsWXkApw/6nm1zZ2KHbUzjfBzsnOJ/Deg2cTvJ3Qq+mC63DgfCBUlTKEdstTWprGD3NVqNJEu0iCsEPwL4PcTaj0ajTbmwy+eABrPMEAeMZK2AyLlHfnOOL1UtUp3f4ZaPKZLmE91Jk4r3gvfDHT9/hrOVm/QrJ7EPMLTzCb6Ee11gFUEkiUIp2J6HdFkohmCSv/AAswmbtd65eXOXhx/f3ZbRN5mYSTBiMZiwi2Cyju705ujfzLeVFSNMMgF6asr76OcZEZN1bhKbE7vkFdpo3sFlKkOtRZLzdbHHi5BmGN7L3nlanS6vVLYoXhY5ymIEIv9bP47xw/uQ5PIrZSmlUiqKSpQgRcM6ROYe1Qmgm2DUzMboS7+i1b9FqdzBRgqZDZXoeE/pxsAgYExfB8Z26we55bJbS62zz1GP7iCbKTJU19Ru1USm01sxWZ/9Tp9na2qJUinnpxeeYmYoxxrB24QJaB4cK8LNP7uX7S5fv3A4Z71VGC9571n9YB2TpjdfffD8EiOOYtw+9Nhw9ClF/DxYRvvxqhWvXNqhdv/7h4pGjhwFC7/3x05+efuduG/Dy8vJ7pz459THgAFF5PgaI8ppN5M8hoIdGmAfZodkCGdABekA6DB4sVg/BBkfID7Vnlc/Dgkk+fP4RP/BRjClbQG//ZchYHUdtI/Y/AcKMnti9YBGeAAAAAElFTkSuQmCC';

Remember to prepend 'data:img/xxx;base64,' to the Base64 encoding. For example, add prefix 'data:img/png;base64,' if your image is PNG.

No comments:

 
Get This <