Reputation: 2699
I am writing a Web Extension for Firefox that needs to insert a substantial amount of additional functionality inside pages retrieved using certain URLs.
I was able to quickly create a content script that is called whenever a certain page is opened thanks to the tutorial at Mozilla's web site, but now I'm stuck on actually inserting html fragment into the page.
I've been at it for hours but to no avail. Here's what I've considered and tried:
iframe
didn't work as apparently some security policy doesn't allow using iframes pointing to local resources and the last comment here even tells that I'm supposed to use panel
instead of iframe
ReferenceError: require is not defined
)innerHTML
but I couldn't find any API to load text from a resourceUpvotes: 1
Views: 778
Reputation: 2699
I can't believe I didn't notice it for so long, but I finally got it all working as I need. While doing that I even came up with an alternative approach, so here goes.
But first here's the main reason why I dismissed all other possible approaches besides using iframe
:
In the end it turned out that the only thing I was missing is the web_accessible_resources
setting in the manifest.json
. Once I added the html file used as source for the iframe
into that list, it all just started working.
// manifest.json:
{
"manifest_version": 2,
...
"web_accessible_resources": [
"data/my.html"
],
"content_scripts": [
{
"matches": ["*://*"],
"js": ["js/my.js"]
}
]
}
// js/my.js
var addonFrame = document.createElement ("IFRAME");
addonFrame.style = "position: absolute; bottom: 0; right: 0; width: 150px; height: 38px;";
addonFrame.frameBorder = "0";
addonFrame.src = chrome.extension.getURL ("data/my.html");
document.body.appendChild (addonFrame);
Before I finally got the first approach working, my experimentation led me to another working approach - inserting HTML into the iframe
directly in the content script.
// js/my.js
var addonFrame = document.createElement ("IFRAME");
addonFrame.style = "position: absolute; bottom: 0; right: 0; width: 150px; height: 38px;";
addonFrame.frameBorder = "0";
var addonHtml = "<!DOCTYPE html>\n\
<html>\n\
<head>\n\
<meta charset='UTF-8'>\n\
<title>Title of the document</title>\n\
</head>\n\
<body>\n\
...\n\
</body>\n\
</html>";
addonFrame.src = 'data:text/html;charset=utf-8,' + encodeURI (addonHtml);
document.body.appendChild (addonFrame);
Even though I ended up using option A in the end, let me outline some pros and cons:
iframe
element in JS).
So it should be easier to support going forward.#
in the inserted html in option B.Window.postMessage
in the frame in order to ask my content script inserted into the original page to make an ajax request and give me back the response (the second part was especially hard since there's nothing like jQuery or Prototype available there).Upvotes: 1