5

I am currently working on a small extension for Chrome. I need same websql database for the extension, but I get different databases based on where I create them.

If I create the database in the content page, I get the database created for a particular page where user is.

If I create database in the background page then I get extension's own database. But it is invisible to content pages.

I wish I could access the EXTENSION's database from content pages, without resorting to clunky message passing mechanism. Is there a way to do that?

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Pavel Zaitsev
  • 578
  • 1
  • 7
  • 12

1 Answers1

3

This is not possible, same thing as with localStorage. Different scripts represent different contexts.

All extension scripts can communicate with background page though. Try creating a proxy API to the database on the background page. This should be simple enough.

I would implement it like this (content script):

chrome.extension.sendRequest({
      method: 'executeSql', 
      sql: 'SELECT title, author FROM docs WHERE id=?',
      params: [10]
   },
   function(response) {
      //do stuff
   }
); 

and on the other end (background page):

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    console.log(request);

    if(request.method == 'executeSql' && request.sql) {
        db.readTransaction(function (t) {
            t.executeSql(request.sql, request.params, function (t, r) {
               //send result with sendResponse
            }, function (t, e) {
               //send error with sendResponse
            });
        });
    } else if(...) { //some other method etc.
    } ...
}

Above code is not tested, it's just a sketch.

Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
  • In the first function call `chrome.extension.sendRequest` you passed a function(response) as the second parameter. I suppose this is meant to be passed by runtime as the third parameter for the listerner function `chrome.extension.onRequest.addListener(function(request, sender, sendResponse)` and consiquently it should be passed as the executeSql callback. However you defined your own inline callbacks for executeSql, so what the `function(response)` is for? – doc_id Dec 31 '12 at 19:34
  • I'm not sure what do you mean. I've checked the docs again (since this answer is quite old) and my code seems OK (although you should use `sendMessage` now since `sendRequest` is deprecated). Content script sends a request to the background page that interacts with DB and returns a result via `sendResponse`. The result is then handled by `function(response)`. Please note that we are using Chrome Extension API here, `sendRequest` and `onRequest` are in different contexts, it's not a 'standard' JS callback passing. – Konrad Dzwinel Jan 06 '13 at 17:05