当使用Google box时,函数调用在Firefox扩展的Javascript代码中不起作用

Function call not working in Javascript code for Firefox extension when using the Google box

本文关键字:扩展 Firefox Javascript 代码 不起作用 函数调用 Google box      更新时间:2023-09-26

我写了一些代码,除了由于未知原因某个函数不起作用(该函数不会被调用为不存在)之外,这些代码运行良好。

我的代码的目的是检测我是否在使用谷歌搜索引擎。它的工作方式是这样的:当用户在谷歌搜索字段上输入关键字并键入enter或单击"搜索"时,url会发生变化,我的代码会检测到它,并显示一个带有页面url的Javascript警报,另一个带有文本"It matches"。

但问题是,当我直接在谷歌框中键入关键词时,它就不起作用了。

我的代码:

    function displayUrl(url)
    { 
       if(url[0].match(/^http:'/'/www'.google'.fr/))
       {
           alert('It matches');
       }
    }
    function getUrlVars(href)
    {
       var vars = [], hash;
       var hashes = href.slice(href.indexOf('?') + 1).split('&');
       for(var i = 0; i < hashes.length; i++)
       {
           hash = hashes[i].split('=');
           vars.push(hash[0]);
           vars[hash[0]] = hash[1];
       }
       displayUrl(vars);
    }
    var myExt_urlBarListener = {
     QueryInterface: function(aIID)
     {
       if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
           aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
           aIID.equals(Components.interfaces.nsISupports))
         return this;
       throw Components.results.NS_NOINTERFACE;
    },
    onLocationChange: function(aProgress, aRequest, aURI)
    {
       myExtension.processNewURL(aURI);
    },
    onStateChange: function(a, b, c, d) {},
    onProgressChange: function(a, b, c, d, e, f) {},
    onStatusChange: function(a, b, c, d) {},
    onSecurityChange: function(a, b, c) {}
    };
    var myExtension = {
     oldURL: null,
     init: function() {
        // Listen for webpage loads
        gBrowser.addProgressListener(myExt_urlBarListener,
            Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);
     },
     uninit: function() {
       gBrowser.removeProgressListener(myExt_urlBarListener);
     },
     processNewURL: function(aURI) {
        if (aURI.spec == this.oldURL)
          return;
       // now we know the url is new...
       alert(aURI.spec);
       /* 
       the following function call doesn't work
       when I type the keyword in the Google box instead of using the Google
       traditionnal search field          
       */
       getUrlVars(aURI.spec);
       this.oldURL = aURI.spec;
     }
  };
  window.addEventListener("load", function() {myExtension.init()}, false);
  window.addEventListener("unload", function() {myExtension.uninit()}, false);

这应该适用于这样的地址

http://domain.com/page.php?http://www.google.fr=something

在displayUrl中,您正在检查提供给getUrlVars()的url的第一个GET参数的键是否匹配http://www.google.fr。我想这不是你想要的^^