【问题标题】:Test http-on-modify-request observer via sdk/system/events?通过 sdk/system/events 测试 http-on-modify-request 观察者?
【发布时间】:2016-05-17 16:45:26
【问题描述】:

是否可以测试http-on-modify-request-Observer?

events module 提供了一个 emit(type, event) 方法来创建 Firefox 事件。要测试监听http-on-modify-request 的模块,您可以将类型设置为http-on-modify-request。问题是如何设置event 参数来模拟网络请求?文档说明

event : object
具有数据和主题属性的可选对象。 data 是指您要传递的字符串 通过这次活动。主题应该是指实际的演员/主题 此事件的原因(即:发出事件的对象)。

设置event.data 被作为观察者的data 参数传递,f.ex 也是如此。一个字符串作为event.subject,但是当我尝试使用QueryInterface-函数传递一个对象时,它不起作用:

events.emit("http-on-modify-request", {"subject": {
    QueryInterface : function() {
        return {"URI": {"spec": 'mock://URI.spec'}}
    }}});

要测试的代码与https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/system_events非常相似。


@humanoid 的使用答案

obs.notifyObservers(
    { QueryInterface : function() {
        return {"URI": NetUtil.newURI("mock://URI.spec") };
    }},
    "http-on-modify-request",
    null);

失败

JavaScript 错误:“NS_NOINTERFACE:组件返回失败代码: 0x80004002 (NS_NOINTERFACE) [nsISupports.QueryInterface]" {文件: “资源://gre/modules/commonjs/toolkit/loader.js -> resource://addon-id/caller.js" 行:xy}]

【问题讨论】:

    标签: javascript events firefox-addon-sdk


    【解决方案1】:

    sdk/system/events 中的 emit 方法对于创建类似于 Firefox 通知的观察者通知没有用处,因为它添加了包装器以确保弱引用。

    相反,我建议使用"vanilla" observer service,例如来自Services.jsm

    const { Services: { obs } } = require("resource://gre/modules/Services.jsm");
    

    【讨论】:

    • 非常感谢您阻止我走这条路。您是否碰巧有一些示例代码?
    • @user 在这种特定情况下使用 nsIObserverService?并不真地。但是 notifyObservers 方法应该很容易使用。
    • 就用这个,我得到了JavaScript Error: "NS_NOINTERFACE: Component returned failure code: 0x80004002 (NS_NOINTERFACE) [nsISupports.QueryInterface]" {file: "resource://gre/modules/commonjs/toolkit/loader.js -> resource://addon-id/caller.js" line: xy}]
    • @user 这里的问题是你没有用你的对象正确地创建一个nsIURI。最好使用const { NetUtil } = require("resource://gre/modules/NetUtil.jsm"); const url = NetUtil.newURI("mock://URI.spec"); 创建nsIURI。有关该方法的文档,请参阅 developer.mozilla.org/en-US/docs/Mozilla/…
    • 使用NetUtil 产生了同样的错误(见上文)
    猜你喜欢
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2021-06-24
    相关资源
    最近更新 更多