简体   繁体   English

通过在附加脚本中查询sqlite db来获取结果以提交给内容脚本

[英]Getting result from querying sqlite db in the add-on script to be submitted to the content script

I am writting a modest firefox add-on and I have some problems getting the results used inside the "flow" of the add-on script. 我正在编写一个适中的firefox插件,但在将结果用于插件脚本的“流”内部时遇到一些问题。

I have the code taking care of querying a sqlite database as a module but I don't know how to create a callback inside of it so that the pagemod in the add-on script can use it and pass it to the content script. 我的代码负责将sqlite数据库作为模块进行查询,但是我不知道如何在其中创建回调,以便附加脚本中的pagemod可以使用它并将其传递给内容脚本。

Basically here is what I have: 基本上这就是我所拥有的:

  • main.js : main.js:
var pageMod = require("sdk/page-mod");
var self = require("sdk/self");
var myDbScript = require('./myDbScript');

pageMod.PageMod({
    include: "*.example.com/*",
    contentScriptFile:  [self.data.url('jquery-1.10.2.min.js'),
                        self.data.url('myContentScript.js')],
    onAttach: function(worker) {
        // Query the database on behalf of the content script
        worker.port.on('queryTheDB', function(message) {            
            // Get the data from the DB (é is some test value here)
            // Not working because asynchronous querying of the DB
            var resultFromDB = myDbScript.getResult(2);

            // Send the result to the content script
            worker.port.emit('hereIsYourResult', resultFromDB);
        });
    }
});
  • myDBScript.js myDBScript.js
// Get required components
var {components} = require("chrome");
components.utils.import("resource://gre/modules/FileUtils.jsm");
components.utils.import("resource://gre/modules/Services.jsm");

// Some code to get the DB

// Create statement to retrieve country based on the IP
var statement = dbConnection.createStatement("SELECT col1, col2 FROM table WHERE col1 = :given_col1");

function getResult(submittedValue) {    
    // Bind parameters
    statement.params.given_col1 = submittedValue;   

    // Execute
    statement.executeAsync({
        handleResult: function(aResultSet) {
            for (let row = aResultSet.getNextRow();
                 row;
                 row = aResultSet.getNextRow()) {

            var resultFromDB = row.getResultByName("col2");
            }
        },

        handleError: function(aError) {
            print("Error: " + aError.message);
            return 'error';
        },

        handleCompletion: function(aReason) {
            if (aReason != components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
                print("Query canceled or aborted!");
                return 'canceledOrAborted';
            } else {
                // Sending the result to the add-on script so that it can
                // pass it to the content script
                notifyingTheAddonScript(resultFromDB);
            }
        }
    });
}

// Enable the use of the getResult function
exports.getResult = getResult;

The thing is that I don't see how to have the addon script be aware that the result is ready. 问题是我不知道如何让插件脚本知道结果已准备好。 Please bear with me, I am a noob at this... 请忍受我,我是这个菜鸟。

Since I don't have the full source, I cannot test. 由于我没有完整的源代码,因此无法测试。 So you'll have to fix any I made errors yourself ;) 因此,您必须自己解决所有我所犯的错误;)

First, lets add a callback. 首先,让我们添加一个回调。

// @param {function(result, error)} callback
// Called upon query completion.
// if |error| is a string, then the query failed.
// Else |result| will contain an array of values. 
function getResult(submittedValue, callback) { // changed   
  // Bind parameters
  statement.params.given_col1 = submittedValue;   

  var rv = [], err = null; // added
  // Execute
  statement.executeAsync({
    handleResult: function(aResultSet) {
      for (let row = aResultSet.getNextRow();
        row;
        row = aResultSet.getNextRow()) {

        rv.push(row.getResultByName("col2")); // changed
      }
    },

    handleError: function(aError) {
      print("Error: " + aError.message);
      err = aError.message; // changed
    },

    handleCompletion: function(aReason) {
      if (aReason != components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
        print("Query canceled or aborted!");
        err = err || 'canceled or aborted'; // changed
      }
      callback(err ? null : rv, err); // replaced
    }
  });
}

Lets use this stuff now in the pagemod 现在让我们在pagemod使用这些东西

onAttach: function(worker) {
  // Query the database on behalf of the content script
  worker.port.on('queryTheDB', function(message) {            
    // Get the data from the DB (é is some test value here)
    // Not working because asynchronous querying of the DB
    myDbScript.getResult(2, function callback(result, error) {
      if (error) {
        worker.port.emit("hereIsYourError", error);
        return;
      }
      worker.port.emit("hereIsYourResult", result);
    });
  });
}

You might want to take some precautions not to fire multiple queries. 您可能需要采取一些预防措施,以免触发多个查询。 While it would be OK to do so, it might hurt performance ;) 这样做虽然可以,但是可能会损害性能;)

Since our callback already looks kinda like a promise , it might actually be a good idea to use promises , maybe even with the Sqlite.jsm module and some Task.jsm magic. 因为我们的回调看起来已经有点像一个promise ,它实际上可能是使用一个好主意的承诺 ,甚至与Sqlite.jsm模块和一些Task.jsm魔术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从后台/内容脚本访问Firefox附加访问弹出脚本? - Firefox add-on access popup script from background/content script? 如何从内容脚本1到附加脚本到内容脚本2获取数据? - How to get data from content script 1 to add-on script to content script 2? 从内容脚本onbeforeunload向附加组件发送消息? - Emit message to add-on from content script onbeforeunload? 从Firefox附加内容脚本复制到剪贴板 - Copy to clipboard from Firefox add-on content script Firefox附加组件的内容脚本不会写入IndexedDB - Content script from Firefox add-on doesn't write to IndexedDB Firefox附加内容脚本中的Crypto getRandomValue - Crypto getRandomValue in Firefox add-on content script Firefox附加组件:(本地应用程序+内容脚本+后台脚本)消息传递 - Firefox add-on: (Native app + Content Script + Background script) messaging 附加SDK调用dispatchEvent不会将事件从内容脚本发送到页面 - Add-on SDK calling dispatchEvent does not send event from content script to a page 如何在 Firefox 控制台中访问附加内容脚本? - How to access add-on content script in Firefox console? 如何知道哪个内容脚本与 Firefox 附加组件中的后台通信? - How to know which content script communicates with the background in a Firefox add-on?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM