Reputation: 50356
I am developing a Firefox addon, how can I open a web browser which is hidden from the user but I can script it from Javascript within my addon code?
Upvotes: 1
Views: 284
Reputation: 33162
SDK users should use the page-worker
module.
XUL add-ons may insert a XUL <iframe type="content">
somewhere and make it hidden (e.g. .style.display = "none";
). Also, you may want to disable images/plugins/script in that <iframe>
.
Assuming window
is a XUL window, such as browser.xul
, here is an example reading the title of a website from a hidden <iframe>
:
function readTitleFromPage(uri, callback) {
callback = callback || function() {};
let frame = document.createElement("iframe");
frame.setAttribute("type", "content");
frame.style.display = "none";
document.documentElement.appendChild(frame);
let docShell = frame.contentWindow.
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIWebNavigation).
QueryInterface(Ci.nsIDocShell);
docShell.allowImages = false;
docShell.allowPlugins = false;
frame.setAttribute("src", uri);
let load = function load(e) {
try {
if (e.type == "load") {
callback(frame.contentDocument.title);
}
else {
callback(null);
}
}
finally {
// Always remove event listeners and the frame itself, at some point.
// In this example, we don't need the frame anymore, beyond this point,
// so remove it now.
frame.removeEventListener("load", load, false);
frame.removeEventListener("error", load, false);
frame.removeEventListener("abort", load, false);
frame.parentElement.removeChild(frame);
}
};
frame.addEventListener("load", load, false);
frame.addEventListener("error", load, false);
frame.addEventListener("abort", load, false);
}
Of course, you can keep around the frame as long as you want, re-use it as many times as you want, and so on. But make sure to remove it once you don't need it anymore, to conserve resources (memory, CPU). Resetting it to about:blank
while not needed might also be a good option.
Upvotes: 2