How to dock a sidebar created with Firefox WebExtensions? - javascript

I've created a sidebar using Firefox WebExtensions, but I'd love to dock the sidebar to the bottom, I did search a lot, and couldn't find anything.
The code I used is this one:
Sidebar.js
var thisPanel = browser.extension.getURL("/this.html");
var thatPanel = browser.extension.getURL("/that.html");
function toggle(panel) {
if (panel === thisPanel) {
browser.sidebarAction.setPanel({panel: thatPanel});
} else {
browser.sidebarAction.setPanel({panel: thisPanel});
}
}
browser.browserAction.onClicked.addListener(() => {
browser.sidebarAction.getPanel({}).then(toggle);
});

Well, it's called a sidebar..
Quoting WebExtension documentation, emphasis mine:
A sidebar is a pane that is displayed at the left-hand side of the browser window, next to the web page.
If you want something docked elsewhere, either you need to inject DOM into the page with content scripts (fragile), or write a devtools.panels extension and dock it within Dev Tools.

This is limited by Webextension standards: you can't call user actions that awaiting promises, because this isn't considered as a "user action handler". Read more here:
Some WebExtension APIs perform functions that are generally performed as a result of a user action. [...]
To follow the principle of "no surprises", APIs like this can only be called from inside the handler for a user action.
There is a good workaround for some alike problems using runtime.connect()

Related

How to simply run listeners on content scripts after an extension is suspended [duplicate]

I have recently converted a GreaseMonkey script of mine into a WebExtension, just to get a first impression of the process. Now I have a reached a point where it would be nice to do some clean-up or simply undo all my changes when said extension is disabled/uninstalled.
From what I've seen on Mozilla's pages, runtime.onSuspend should do the trick. Unfortunately, it looks like that's not yet implemented (I'm on the regular Firefox release channel).
In other words, what I want to do is run code as a result of the user removing/disabling my extension so that I can clean-up listeners and such and generally restore the tabs to their status quo, i. e., undo all the changes the extension made.
The other answer is incorrect. The first part (about the onSuspend event) is factually incorrect. The part about setUninstallURL is relevant, but does not answer the question since it does not allow you to restore tabs to their original state (as you asked in the question).
In this answer I will first clear the misconception about runtime.onSuspend, and then explain how you can run code for a content script when an extension is disabled.
About runtime.onSuspend
The chrome.runtime.onSuspend and chrome.runtime.onSuspendCanceled events have nothing to do with a disabled/uninstalled extension. The events are defined for event pages, which are basically background pages that are suspended (unloaded) after a period of inactivity. When the event page is about to unload due to suspension, runtime.onSuspend is called. If an extension API is called during this event (e.g. sending an extension message), the suspension will be canceled and trigger the onSuspendCanceled event.
When an extension is unloading because of a browser shutdown or an uninstallation, the lifetime of the extension cannot be extended. Thus you cannot rely on these events to run asynchronous tasks (such as cleaning up tabs from the background page).
Furthermore, these events are not available in content scripts (only extension pages such as background pages), so these cannot be used to synchronously clean up content script logic.
From the above it should be obvious that runtime.onSuspend is not remotely relevant for the goal of clean-up upon disable. Not in Chrome, let alone Firefox (Firefox does not support event pages, these events would be meaningless).
Running code in tabs/content scripts upon extension disable/uninstall
A common pattern in Chrome extensions is to use the port.onDisconnect event to detect that the background page has unloaded, and use that to infer that the extension might have unloaded (combined with option 1 of this method for a higher accuracy). Chrome's content scripts are kept around after an extension is disabled, so this can be used to run asynchronous clean-up code.
This is not possible in Firefox, because the execution context of a content script is destroyed when a Firefox extension is disabled, before the port.onDisconnect event has a chance to fire (at least, until bugzil.la/1223425 is fixed).
Despite these constraints, it is still possible to run clean up logic for a content script when an add-on is disabled. This method is based on the fact that in Firefox, style sheets inserted with tabs.insertCSS are removed when an add-on is disabled.
I will discuss two ways to exploit this characteristic. The first method allows execution of arbitrary code. The second method does not provide execution of arbitrary code, but it is simpler and sufficient if you only want to hide some extension-inserted DOM elements.
Method 1: Run code in page when extension is disabled
One of the ways to observe style changes is by declaring CSS transitions and using transition events to detect CSS property changes.
For this to be helpful, you need to construct a style sheet in such a way that it only affects your HTML elements. So you need to generate a unique selector (class name, ID, ...) and use that for your HTML element(s) and style sheet.
This is code that you have to put in your background script:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message !== 'getStyleCanary') return;
// Generate a random class name, insert a style sheet and send
// the class back to the caller if successful.
var CANARY_CLASS = '_' + crypto.getRandomValues(new Uint32Array(2)).join('');
var code = '.' + CANARY_CLASS + ' { opacity: 0 !important; }';
chrome.tabs.insertCSS(sender.tab.id, {
code,
frameId: sender.frameId,
runAt: 'document_start',
}, function() {
if (chrome.runtime.lastError) {
// Failed to inject. Frame unloaded?
sendResponse();
} else {
sendResponse(CANARY_CLASS);
}
});
return true; // We will asynchronously call sendResponse.
});
In the content script:
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// NOTE: Consider retry sending the message in case
// the background page was not ready yet.
return;
}
var s = document.createElement('script');
s.src = chrome.runtime.getURL('canaryscript.js');
s.onload = s.remove;
s.dataset.canaryClass = CANARY_CLASS;
// This function will become available to the page and be used
// by canaryscript.js. NOTE: exportFunction is Firefox-only.
exportFunction(function() {}, s, {defineAs: 'checkCanary'});
(document.body || document.documentElement).appendChild(s);
});
I use a script tag above, because it is the only way to run a script in the page without being blocked by the page's content security policy. Make sure that you add canaryscript.js to web_accessible_resources in manifest.json, or else the script won't load.
If running the cleanup code is not critical (e.g. because you also use method 2 which I explain later), then you should preferably use inline scripts instead of external scripts (i.e. use s.textContent = '<content of canaryscript.js>' instead of s.src = ...). This is because using .src with extension resources introduces a fingerprinting vulnerability to Firefox (bug 1372288).
This is the content of canaryscript.js:
(function() {
// Thes two properties are set in the content script.
var checkCanary = document.currentScript.checkCanary;
var CANARY_CLASS = document.currentScript.dataset.canaryClass;
var canary = document.createElement('span');
canary.className = CANARY_CLASS;
// The inserted style sheet has opacity:0. Upon removal a transition occurs.
canary.style.opacity = '1';
canary.style.transitionProperty = 'opacity';
// Wait a short while to make sure that the content script destruction
// finishes before the style sheet is removed.
canary.style.transitionDelay = '100ms';
canary.style.transitionDuration = '1ms';
canary.addEventListener('transitionstart', function() {
// To avoid inadvertently running clean-up logic when the event
// is triggered by other means, check whether the content script
// was really destroyed.
try {
// checkCanary will throw if the content script was destroyed.
checkCanary();
// If we got here, the content script is still valid.
return;
} catch (e) {
}
canary.remove();
// TODO: Put the rest of your clean up code here.
});
(document.body || document.documentElement).appendChild(canary);
})();
Note: CSS transition events are only fired if the tab is active. If the tab is inactive, the transition event will not fire until the tab is shown.
Note: exportFunction is a Firefox-only extension method to define a function in a different execution context (in the above example, the function was defined in the page's context, available to scripts running in that page).
All other APIs are available in other browsers too (Chrome/Opera/Edge), but the code cannot be used to detect disabled extensions, because style sheets from tabs.insertCSS are not removed upin uninstall (I only tested with Chrome; it might work in Edge).
Method 2: Visual restoration upon uninstallation
Method 1 allows you to run arbitrary code, such as removing all elements that you inserted in the page. As an alternative to removing the elements from the DOM, you can also choose to hide the elements through CSS.
Below I show how you can modify method 1 to hide the elements without running other code (such as canaryscript.js).
When your content script creates an element for insertion in the DOM, you hide it with an inline style:
var someUI = document.createElement('div');
someUI.style.display = 'none'; // <-- Hidden
// CANARY_CLASS is the random class (prefix) from the background page.
someUI.classList.add(CANARY_CLASS + 'block');
// ... other custom logic, and add to document.
In the style sheet that you add with tabs.insertCSS, you then define the desired display value, with the !important flag so that the inline style is overridden:
// Put this snippet after "var code = '.' + CANARY_CLASS, above.
code += '.' + CANARY_CLASS + 'block {display: block !important;}';
The above example is intentionally generic. If you have multiple UI elements with different CSS display values (e.g. block, inline, ...), then you can add multiple of these lines to re-use the framework that I provided.
To show the simplicity of method 2 over method 1: you can use the same background script (with the above modification), and use the following in the content script:
// Example: Some UI in the content script that you want to clean up.
var someUI = document.createElement('div');
someUI.textContent = 'Example: This is a test';
document.body.appendChild(someUI);
// Clean-up is optional and a best-effort attempt.
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// Do not add clean-up classes.
return;
}
someUI.classList.add(CANARY_CLASS + 'block');
someUI.style.display = 'none';
});
If your extension has more than one element, consider caching the value of CANARY_CLASS in a local variable so that you only insert one new style sheet per execution context.
Your initial wording was somewhat unclear as to exactly what you desire. Thus, this answer also contains information on one way you could receive a notification of the uninstall, under some conditions.
Run code in your WebExtension add-on prior to uninstall/disable:
No, even if it was supported, the runtime.onSuspend event would not do what you want. It's used to signal Event Pages that they are about to be unloaded. Even Pages are unloaded routinely when the handling of the events they are listening for has completed. It is not an indication that the extension is being uninstalled.
"Determine" that your "WebExtension was disabled/uninstalled":
If your question is really what you state in the last line of your question: "... is there a way to determine whether a WebExtension was disabled/uninstalled?" Then, it looks like you could use runtime.setUninstallURL(), which was implemented as of Firefox 47. This will allow you to set a URL to visit when the add-on is uninstalled. This could be used on your server to note that the add-on was uninstalled. It does not inform your WebExtension that it was uninstalled, nor permit you to run code in your WebExtension when that happens.
Unfortunately, you can not use detecting, in your WebExtension, that this URL was visited as indicating your WebExtension is being uninstalled/disabled. Based on testing, this URL is visited after the WebExtension has been completely uninstalled. In addition, it is not visited upon the WebExtension being disabled, nor when uninstalled after being disabled. It is only visited when the WebExtension is uninstalled while the add-on is enabled. From the fact that this is a JavaScript call which is only run when the extension is enabled, one would expect that the page would only be opened when leaving the enabled state.
Testing was done by adding the following line to a WebExtension and seeing when the page was opened:
chrome.runtime.setUninstallURL("http://www.google.com");
Given how this actually functions (only visited if the WebExtension is enabled and directly uninstalled), using this as "a way to determine whether a WebExtension was disabled/uninstalled" will only be partially effective. As should be clear, you will not be notified by a visit to this URL if the add-on is disabled prior to being uninstalled.

Firefox WebExtension: How Do I Run Code Prior to Disable/Uninstall?

I have recently converted a GreaseMonkey script of mine into a WebExtension, just to get a first impression of the process. Now I have a reached a point where it would be nice to do some clean-up or simply undo all my changes when said extension is disabled/uninstalled.
From what I've seen on Mozilla's pages, runtime.onSuspend should do the trick. Unfortunately, it looks like that's not yet implemented (I'm on the regular Firefox release channel).
In other words, what I want to do is run code as a result of the user removing/disabling my extension so that I can clean-up listeners and such and generally restore the tabs to their status quo, i. e., undo all the changes the extension made.
The other answer is incorrect. The first part (about the onSuspend event) is factually incorrect. The part about setUninstallURL is relevant, but does not answer the question since it does not allow you to restore tabs to their original state (as you asked in the question).
In this answer I will first clear the misconception about runtime.onSuspend, and then explain how you can run code for a content script when an extension is disabled.
About runtime.onSuspend
The chrome.runtime.onSuspend and chrome.runtime.onSuspendCanceled events have nothing to do with a disabled/uninstalled extension. The events are defined for event pages, which are basically background pages that are suspended (unloaded) after a period of inactivity. When the event page is about to unload due to suspension, runtime.onSuspend is called. If an extension API is called during this event (e.g. sending an extension message), the suspension will be canceled and trigger the onSuspendCanceled event.
When an extension is unloading because of a browser shutdown or an uninstallation, the lifetime of the extension cannot be extended. Thus you cannot rely on these events to run asynchronous tasks (such as cleaning up tabs from the background page).
Furthermore, these events are not available in content scripts (only extension pages such as background pages), so these cannot be used to synchronously clean up content script logic.
From the above it should be obvious that runtime.onSuspend is not remotely relevant for the goal of clean-up upon disable. Not in Chrome, let alone Firefox (Firefox does not support event pages, these events would be meaningless).
Running code in tabs/content scripts upon extension disable/uninstall
A common pattern in Chrome extensions is to use the port.onDisconnect event to detect that the background page has unloaded, and use that to infer that the extension might have unloaded (combined with option 1 of this method for a higher accuracy). Chrome's content scripts are kept around after an extension is disabled, so this can be used to run asynchronous clean-up code.
This is not possible in Firefox, because the execution context of a content script is destroyed when a Firefox extension is disabled, before the port.onDisconnect event has a chance to fire (at least, until bugzil.la/1223425 is fixed).
Despite these constraints, it is still possible to run clean up logic for a content script when an add-on is disabled. This method is based on the fact that in Firefox, style sheets inserted with tabs.insertCSS are removed when an add-on is disabled.
I will discuss two ways to exploit this characteristic. The first method allows execution of arbitrary code. The second method does not provide execution of arbitrary code, but it is simpler and sufficient if you only want to hide some extension-inserted DOM elements.
Method 1: Run code in page when extension is disabled
One of the ways to observe style changes is by declaring CSS transitions and using transition events to detect CSS property changes.
For this to be helpful, you need to construct a style sheet in such a way that it only affects your HTML elements. So you need to generate a unique selector (class name, ID, ...) and use that for your HTML element(s) and style sheet.
This is code that you have to put in your background script:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message !== 'getStyleCanary') return;
// Generate a random class name, insert a style sheet and send
// the class back to the caller if successful.
var CANARY_CLASS = '_' + crypto.getRandomValues(new Uint32Array(2)).join('');
var code = '.' + CANARY_CLASS + ' { opacity: 0 !important; }';
chrome.tabs.insertCSS(sender.tab.id, {
code,
frameId: sender.frameId,
runAt: 'document_start',
}, function() {
if (chrome.runtime.lastError) {
// Failed to inject. Frame unloaded?
sendResponse();
} else {
sendResponse(CANARY_CLASS);
}
});
return true; // We will asynchronously call sendResponse.
});
In the content script:
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// NOTE: Consider retry sending the message in case
// the background page was not ready yet.
return;
}
var s = document.createElement('script');
s.src = chrome.runtime.getURL('canaryscript.js');
s.onload = s.remove;
s.dataset.canaryClass = CANARY_CLASS;
// This function will become available to the page and be used
// by canaryscript.js. NOTE: exportFunction is Firefox-only.
exportFunction(function() {}, s, {defineAs: 'checkCanary'});
(document.body || document.documentElement).appendChild(s);
});
I use a script tag above, because it is the only way to run a script in the page without being blocked by the page's content security policy. Make sure that you add canaryscript.js to web_accessible_resources in manifest.json, or else the script won't load.
If running the cleanup code is not critical (e.g. because you also use method 2 which I explain later), then you should preferably use inline scripts instead of external scripts (i.e. use s.textContent = '<content of canaryscript.js>' instead of s.src = ...). This is because using .src with extension resources introduces a fingerprinting vulnerability to Firefox (bug 1372288).
This is the content of canaryscript.js:
(function() {
// Thes two properties are set in the content script.
var checkCanary = document.currentScript.checkCanary;
var CANARY_CLASS = document.currentScript.dataset.canaryClass;
var canary = document.createElement('span');
canary.className = CANARY_CLASS;
// The inserted style sheet has opacity:0. Upon removal a transition occurs.
canary.style.opacity = '1';
canary.style.transitionProperty = 'opacity';
// Wait a short while to make sure that the content script destruction
// finishes before the style sheet is removed.
canary.style.transitionDelay = '100ms';
canary.style.transitionDuration = '1ms';
canary.addEventListener('transitionstart', function() {
// To avoid inadvertently running clean-up logic when the event
// is triggered by other means, check whether the content script
// was really destroyed.
try {
// checkCanary will throw if the content script was destroyed.
checkCanary();
// If we got here, the content script is still valid.
return;
} catch (e) {
}
canary.remove();
// TODO: Put the rest of your clean up code here.
});
(document.body || document.documentElement).appendChild(canary);
})();
Note: CSS transition events are only fired if the tab is active. If the tab is inactive, the transition event will not fire until the tab is shown.
Note: exportFunction is a Firefox-only extension method to define a function in a different execution context (in the above example, the function was defined in the page's context, available to scripts running in that page).
All other APIs are available in other browsers too (Chrome/Opera/Edge), but the code cannot be used to detect disabled extensions, because style sheets from tabs.insertCSS are not removed upin uninstall (I only tested with Chrome; it might work in Edge).
Method 2: Visual restoration upon uninstallation
Method 1 allows you to run arbitrary code, such as removing all elements that you inserted in the page. As an alternative to removing the elements from the DOM, you can also choose to hide the elements through CSS.
Below I show how you can modify method 1 to hide the elements without running other code (such as canaryscript.js).
When your content script creates an element for insertion in the DOM, you hide it with an inline style:
var someUI = document.createElement('div');
someUI.style.display = 'none'; // <-- Hidden
// CANARY_CLASS is the random class (prefix) from the background page.
someUI.classList.add(CANARY_CLASS + 'block');
// ... other custom logic, and add to document.
In the style sheet that you add with tabs.insertCSS, you then define the desired display value, with the !important flag so that the inline style is overridden:
// Put this snippet after "var code = '.' + CANARY_CLASS, above.
code += '.' + CANARY_CLASS + 'block {display: block !important;}';
The above example is intentionally generic. If you have multiple UI elements with different CSS display values (e.g. block, inline, ...), then you can add multiple of these lines to re-use the framework that I provided.
To show the simplicity of method 2 over method 1: you can use the same background script (with the above modification), and use the following in the content script:
// Example: Some UI in the content script that you want to clean up.
var someUI = document.createElement('div');
someUI.textContent = 'Example: This is a test';
document.body.appendChild(someUI);
// Clean-up is optional and a best-effort attempt.
chrome.runtime.sendMessage('getStyleCanary', function(CANARY_CLASS) {
if (!CANARY_CLASS) {
// Background was unable to insert a style sheet.
// Do not add clean-up classes.
return;
}
someUI.classList.add(CANARY_CLASS + 'block');
someUI.style.display = 'none';
});
If your extension has more than one element, consider caching the value of CANARY_CLASS in a local variable so that you only insert one new style sheet per execution context.
Your initial wording was somewhat unclear as to exactly what you desire. Thus, this answer also contains information on one way you could receive a notification of the uninstall, under some conditions.
Run code in your WebExtension add-on prior to uninstall/disable:
No, even if it was supported, the runtime.onSuspend event would not do what you want. It's used to signal Event Pages that they are about to be unloaded. Even Pages are unloaded routinely when the handling of the events they are listening for has completed. It is not an indication that the extension is being uninstalled.
"Determine" that your "WebExtension was disabled/uninstalled":
If your question is really what you state in the last line of your question: "... is there a way to determine whether a WebExtension was disabled/uninstalled?" Then, it looks like you could use runtime.setUninstallURL(), which was implemented as of Firefox 47. This will allow you to set a URL to visit when the add-on is uninstalled. This could be used on your server to note that the add-on was uninstalled. It does not inform your WebExtension that it was uninstalled, nor permit you to run code in your WebExtension when that happens.
Unfortunately, you can not use detecting, in your WebExtension, that this URL was visited as indicating your WebExtension is being uninstalled/disabled. Based on testing, this URL is visited after the WebExtension has been completely uninstalled. In addition, it is not visited upon the WebExtension being disabled, nor when uninstalled after being disabled. It is only visited when the WebExtension is uninstalled while the add-on is enabled. From the fact that this is a JavaScript call which is only run when the extension is enabled, one would expect that the page would only be opened when leaving the enabled state.
Testing was done by adding the following line to a WebExtension and seeing when the page was opened:
chrome.runtime.setUninstallURL("http://www.google.com");
Given how this actually functions (only visited if the WebExtension is enabled and directly uninstalled), using this as "a way to determine whether a WebExtension was disabled/uninstalled" will only be partially effective. As should be clear, you will not be notified by a visit to this URL if the add-on is disabled prior to being uninstalled.

addon firefox - open window with specific dimensions

I have made an addon for firefox. I install it but i have two problems.I use windows.open because the panel isn`t suitable for me because if the user want to copy something in it, the panel is disappearing when he leaves it. So i have windows. I have this code:
var widgets = require("sdk/widget");
var windows = require("sdk/windows").browserWindows;
var self = require("sdk/self");
var widget = widgets.Widget({
id: "open window",
label: "test",
contentURL: self.data.url("favicon.ico"),
onClick: function() {
windows.open({
url: "http://www.example.com",
onOpen: function(window) {
}
});
}
});
I don`t know where to put the attributes of width,height,no scroll :/ in order to be displayd as a popup window.
And the second problem is that the button is displayed at the bar of addons.How it is possible to display it at the nav bar next to firebug?
The windows module does not support specifying window features.
You could use the unstable window/utils module and the openDialog function to provides.
Or you could get yourself chrome privileges and re-implement the stuff yourself. The implementation of openDialog is surprisingly pretty straight forward and can be borrowed from easily.
Either way, you'll need to wait for a window to actually fully load (newWindow.addEventListener("load", ...)) before you can safely interact with it. Or get somewhat hackish and listen for the first open event via the windows module.

In JavaScript, what is event.isTrigger?

I came across this in some JS code I was working on:
if ( typeof( e.isTrigger ) == 'undefined' ) {
// do some stuff
}
This seems to be part of jQuery. As far as I can see it tells you if an event originated with the user or automatically.
Is this right? And given that it's not documented, is there a way of finding such things out without going behind the curtain of the jQuery API?
In jQuery 1.7.2 (unminified) line 3148 contains event.isTrigger = true; nested within the trigger function. So yes, you are correct - this is only flagged when you use .trigger() and is used internally to determine how to handle events.
If you look at jQuery github project, inside trigger.js file line 49 (link here) you can find how isTrigger gets calculated.
If you add a trigger in your JavaScript and debug through, You can see how the breakpoint reaches this codeline (checked in jQuery-2.1.3.js for this SO question)
Modern browsers fight against popup windows opened by automated scripts, not real users clicks. If you don't mind promptly opening and closing a window for a real user click and showing a blocked popup window warning for an automated click then you may use this way:
button.onclick = (ev) => {
// Window will be shortly shown and closed for a real user click.
// For automated clicks a blocked popup warning will be shown.
const w = window.open();
if (w) {
w.close();
console.log('Real user clicked the button.');
return;
}
console.log('Automated click detected.');
};

Communication between firefox extension and page javascript

I am developing a web-based javascript/html application with a sister firefox-extension.
The application's page-javascript performs a few XHR calls immediately after page-load, in order to bring in and display all the content that the page requires.
Is there a way, without polling the DOM, that my extension can know that the page's initialisation procedures are complete?
Interesting question indeed..
I've just found out through this post on MozillaZine's forum an easy way to accomplish this. The technique basically consists in defining a custom DOM element within the web page, filling it with some arbitrary attributes, and then using it as the target of a custom event. The event can than be captured and used to pass values from the webpage to the extension.
Web page (assumes jquery is available)
<script type="text/javascript">
$(document).ready(function(){
$.get("http://mywebsite.net/ajax.php",function(data){
//[...]process data
//define a custom element and append it to the document
var element = document.createElement("MyExtensionDataElement");
element.setAttribute("application_state", "ready");
document.documentElement.appendChild(element);
//create a custom event and dispatch it
// using the custom element as its target
var ev = document.createEvent("Events");
ev.initEvent("MyExtensionEvent", true, false);
element.dispatchEvent(ev);
});
});
</script>
Chrome code:
function myListener(e) {
alert("data:" + e.target.getAttribute("application_state"));
}
function on_specialpage_load(event) {
if (event.originalTarget instanceof HTMLDocument &&
event.originalTarget.location.href == "http://mywebsite.net/myspecialpage.html") {
var doc=event.originalTarget;
doc.addEventListener("MyExtensionEvent", myListener, false, true);
}
}
gBrowser.addEventListener("DOMContentLoaded",on_specialpage_load,false);
Notice that doc.addEventListener has a fourth parameter, indicating that it will accept events coming from untrusted code. However you can add this event listener selectively, so that only trusted pages from your site will be able to pass values to the extension.
You could hook into the XMLHttpRequest object from your extension and monitor the requests, similar to what this GreaseMonkey script does (description). Add a wrapper to onreadystatechange in the same way he's added a wrapper to open which notifies the extension when complete. Probably also want some code which makes sure you're only doing this when visiting your own page.
Firebug does similar stuff for its Net panel, the codebase for that is a bit more intimidating though :) I also had a look at the Firebug Lite watchXHR function, but that code is a bit too cunning for me, if you can work it out let me know.

Categories