如何取消http请求?

时间:2011-05-30 15:12:28

标签: javascript firefox firefox-addon

我正在尝试使用aSubject.cancel(Components.results.NS_BINDING_SUCCEEDED);取消HTTP请求,但它不起作用。代码如下。有人可以纠正吗?

function(aSubject, aTopic, aData)
{
    if ("http-on-modify-request" == aTopic)
    {
        //get the http request url
            var url = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel).originalURI.spec;

        //get the referer of http request (this error gives an error; dont know why :( 
        var a = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel).getRequestHeader("referer");

        //Cancel http request from other domains 
        if (url.split('//')[1].split('/')[0] != a.split('//')[1].split('/')[0])
        {
            //the code below don't work! Someone please correct it.
            //code to cancel http request
            aSubject.cancel(Components.results.NS_BINDING_SUCCEEDED);
            }
    }
}

1 个答案:

答案 0 :(得分:2)

这可能是因为NS_BINDING_SUCCEEDED不是错误代码(是的,文档似乎是错误的)。您实际想要使用的是Components.results.NS_BINDING_ABORTED

顺便说一下,您似乎在比较URL中的主机名。鉴于您已经有一个nsIURI对象,这可以更轻松地完成:

var requestHost = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel).originalURI.host;
var referrerHost = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel).referrer.host;
if (requestHost != referrerHost)
{
    aSubject.cancel(Components.results.NS_BINDING_ABORTED);
}