Search code examples
javascripthtmlfirefox-addonfirefox-addon-sdk

Panel content and script reloaded everytime button is clicked


This is a very simple Firefox addon which:

  • adds a Widget to addon bar
  • attachs a Panel to the Widget
  • the Panel's content contains an input element and 2 buttons

When I click the Widget, the Panel is shown, as expected.
But when I click testButton, console.log('loaded'); is printed to console.
Why is the Panel's content and scripts reloaded even though I'm not updating the Panel?

Another testcase (with same behaviour), if I enter a value into inputField and then click testButton, inputField's value is reset to be empty.

Addon code, main.js:

require("./Panel").init();

Module, Panel.js:

var Panel = require("sdk/panel"),
    Data = require("./Data")
    Widget = require("./Widget");

exports.init = function(){
    ui = Panel.Panel({
        width: 180,
        height: 180,
        contentURL: Data.get("html/Presentation.html"),
        contentScriptFile: Data.get("js/Logic.js"),
        onShow: function() { console.log("showing"); }
    });

    Widget.init(ui);
}

Another module, Widget.js:

var widget = require("sdk/widget"),
    Data = require("./Data");

exports.init = function(panel) {

    widget.Widget({
        id: "test-widget",
        label: "PanelTest",
        contentURL: Data.get("images/ico.png"),
        panel: panel
    });
}

Last module, Data.js:

var data = require("sdk/self").data;

exports.get = function(content) {

    return data.url(content);
}

contentURL for panel, Presentation.html:

<html>
    <head>
        <meta charset="UTF-8" />
    </head>
    <body>
        <form>
            <table>
                <tr>
                    <input id="inputField" type="text" size="10"></input>
                </tr>
                <tr>
                    <td>
                        <button id="testButton">Test</button>
                    </td>
                </tr>
                <tr>
                    <td>
                        <button id="evaluate">evaluate</button>
                    </td>
                </tr>
            </table>
        </form>
    </body> 
</html>

contentScriptFile for panel, Logic.js:

window.onload=function(){
    console.log('loaded');

    var button = document.getElementById("evaluate");
    button.addEventListener("click", function() { 
        console.log("evaluate clicked");
    });
};

Solution

  • Try adding type='button' to your buttons, as this attribute defaults to 'submit'.

    From MDN, under the type attribute:

    submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.