Firefox XUL toolbar problem with javascript getElementById
I'm writing my first Firefox XUL toolbar, and am getting a strange behavior - in order to debug my code, I call the same js function from both the firefox toolbar and from a button on a very simple HTML file I created.
The javascript function displays an alert window, gets an element using 'document.getElementById', changes its color, and displays another alert window.
The javascript function works well when called using the HTML button, but when using the toolbar button the 'document.getElementById' returns null and the function terminates (only the first alert window shows).
Any guess what can be wrong? I provi开发者_开发知识库de the (very simple) code below for refenrece.
Many thanks in advance!
The javascript file - facebrew.js
function FaceBrew_rtlSelection() {
alert('Before!');
sel_node = document.getElementById("header");
sel_node.style.color = 'blue';
alert('After!');
}
The HTML file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript" src="http://localhost/Sandbox/FaceBrew/chrome/content/facebrew.js"> </script>
</head>
<body>
<input type="button" value="Click me" id="select" onclick="FaceBrew_rtlSelection()" />
<div id="header">
<h1>Hello world!< /h1>
</div>
</body>
</html>
The XUL file - facebrew.xul
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://facebrew/skin/facebrew.css" type="text/css"?>
<overlay id="FaceBrew-Overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript"
src="chrome://facebrew/content/facebrew.js" />
<toolbox id="navigator-toolbox">
<toolbar id="FaceBrew-Toolbar" toolbarname="FaceBrew Toolbar" accesskey="F"
class="chromeclass-toolbar" context="toolbar-context-menu"
hidden="false" persist="hidden">
<toolbaritem flex="0">
<toolbarbutton id="FaceBrew-Web-Button" tooltiptext=""
label="Run" oncommand="FaceBrew_rtlSelection()" />
</toolbaritem>
</toolbar>
</toolbox>
</overlay>
The CSS file - facbrew.css
#FaceBrew-Web-Button {
list-style-image: url("chrome://facebrew/skin/web.png");
}
as Paul said, when function is called from toolbar, document context is different. get your currently selected HTML document object with:
var doc = gBrowser.selectedBrowser.contentDocument;
doc.getElementById(...);
also, you can always take a look at error console to see why your code is failing (Tools -> Error Console).
Your toolbar is an overlay, so the context (document and window) is browser.xul, no your html file.
精彩评论