Why does this XUL code works and the Javascript equivalent doesn't?
xul way:
<toolbar id="PersonalToolbar">
<toolbarbutton
id="Testing-Doit-Button2"
class="bookmark-item pagerank"
tooltiptext="Do it!"
oncommand="testing_doit();"
/>
</toolbar>
javascript way:
function createBookmarkItem() {
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var item = document.createElementNS(XUL_NS, "toolbarbutton");
item.setAttribute("id", "Testing-Doit-Button2");
item.setAttribute("class", "bookmark-item pagerank");
item.setAttribute("tooltiptext", "Do it!");
item.setAttribute("oncommand", "testing_doit();");
return item;
}
function placeBookmarkItem() {
var toolbar = document.getElementById("PersonalToolbar");
var button = createBookmarkItem();
toolbar.appendChild(button);
}
placeBookmarkItem();
The xul way shows a button. The Javascript way shows a button when I go to the Javascript Shell of the Extension Developer's Extension, then click enumerateWindows(), then click chrome://browser/content/browser.xul, then type the code, then hit enter. The Javascri开发者_如何学编程pt way doesn't show a button when I include button.js in button.xul. Why?
You need to place the placeBookmarkItem(); inside the documents onload event. The javascript gets executed before the document is in place.
Otherwise place the <script/>
element just before the </window>
element in the end of the document.
A part of the code that I didn't quote here and that had an error made not work the part of the code that I quoted here and that didn't have an error. Take a look at "I add 10 functions to a code, I don’t even call any of them, but the code stops working!" for more information.
精彩评论