Search code examples
javascriptsqlitepermissionsstoragemozilla

Mozilla storageService: "Cannot execute statement :Error: Permission denied "


(cross-posted on Mozilla: http://forums.mozillazine.org/viewtopic.php?f=7&t=2254955 )

I'm trying to work with the Mozilla storageService. In the following code, the user is asked to grant the creation of a local database ('database.sqlite') and a table is created.

<html>
<head>
<script type="text/javascript">
var con=null;
function executeStatement()
    {
    try
        {
        var stmt=con.createStatement("SELECT * FROM instances");
        }
    catch(e)
        {
        alert("Cannot execute statement :"+e);
        }
    }

function init()
    {
    try
        {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        }
    catch (e)
        {
        alert("Permission to write to file was denied.");
        return;
        }

    try
        {
        var file = Components.classes["@mozilla.org/file/directory_service;1"]
                     .getService(Components.interfaces.nsIProperties)
                     .get("Home", Components.interfaces.nsIFile);
        file.append("database.sqlite");

        var storageService = Components.classes["@mozilla.org/storage/service;1"]
                        .getService(Components.interfaces.mozIStorageService);
        con = storageService.openDatabase(file);
        con.executeSimpleSQL(
            "CREATE TABLE IF NOT EXISTS instances("+
                "id INTEGER PRIMARY KEY AUTOINCREMENT"+
            ")"
            );
        }
    catch(e)
        {
        alert(e);
        }

    }


window.addEventListener("load", init,true); 
</script>
</head>
<body>
<button onClick="executeStatement();">Test</button>
</body>
</html>

But when I click on the button to invoke the method executeStatement, I get the following exception:

Cannot execute statement :Error: Permission denied for <file://> to call method UnnamedClass.createStatement

why ?


Solution

  • That's just how enablePrivilege works - you have to call it in every function requiring the privileges. See also The only option is to include that block of code into each of my functions?

    While we're at it, I'll quote bz's comment from that thread:

    I strongly suggest you look into not using enablePrivilege at all. It's deprecated and on its way to being removed. – Boris Zbarsky Jul 13 at 14:10

    ...

    The replacement is using an extension. I'm not sure how clearly documented this is, but upcoming Firefox versions will warn when you use enablePrivilege, and you can no longer use enablePrivilege to do cross-site XMLHttpRequest. There's mention of this in some places (e.g. https://developer.mozilla.org/en/Mochitest#How_can_I_get_around_the_error_.22Permission_denied_to_get_property_XPCComponents.classes.22.3f ) but a lot more documentation to update yet. – Boris Zbarsky Jul 14 at 5:11