代码之家  ›  专栏  ›  技术社区  ›  Paul

如何知道哪个网页正在调用外部javascript脚本

  •  0
  • Paul  · 技术社区  · 14 年前

    5 回复  |  直到 14 年前
        1
  •  6
  •   Igor Zevaka    14 年前

    location object 包含有关浏览器当前所在URL的所有信息。

        hash        Returns the anchor portion of a URL
        host        Returns the hostname and port of a URL
        hostname    Returns the hostname of a URL
        href        Returns the entire URL
        pathname    Returns the path name of a URL
        port        Returns the port number the server uses for a URL
        protocol    Returns the protocol of a URL
        search      Returns the query portion of a URL
    

    现在,回答您真正想问的问题,即如何跟踪哪些页面正在使用您的javascript文件。我认为(我以前没有实现过这样的东西)是使用与分析网站相同的策略。

    它们似乎都使用了一种跟踪像素的变体,浏览器在其中下载脚本文件(例如QuantServer)- http://edge.quantserve.com/quant.js

    http://pixel.quantserve.com/pixel;r=3547206;fpan=0;fpa=P0-82955756-1264139666260;ns=0;url=http%3A%2F%2Fstackoverflow.com .... (我没有透露地址,因为它是我的浏览器发送它,因为我真的不知道它揭示了什么关于我:))。

    之所以这是一个图像而不是AJAX请求,是因为AJAX请求受浏览器XSS限制。基本上,浏览器不会对不提供页面服务的网站进行AJAX调用。这意味着www.otherpeopleswebsite.com 不允许对www.mywebsite.com. 对图像(或javascript文件)没有这样的限制。

    所以一个简单的系统来实现这样的效果:

    //s.js
    var oldLoad = window.onload;
    window.onload = function(){
      if (oldLoad)
        oldLoad();
        var img = document.createElement('img');
        img.setAttribute('src', 'www.mysite.com/pixel?url=' + window.location.href);
    }
    

    在服务器端, pixel image/gif ),提取查询字符串并记录URL。根据您的服务器技术,有许多方法可以实现这一点。

        2
  •  1
  •   Pointy    14 年前

    脚本可以参考 document.location ,它将始终围绕主页的URL构建。明确地, document.location.href 将是URL。

    因此:

    if (document.location.href === 'http://www.cnn.com') {
      // being imported by CNN ...
    }
    

        3
  •  1
  •   vol7ron    14 年前

    在javascript文件中,需要对记录文件名的脚本进行AJAX调用。日志可以是数据库或平面文件。你得把 location.href (或财产) location

    嵌入在Javascript文件中,您需要将函数附加到windows onload或domready事件,以确保执行AJAX调用。确保不要重写onload/domready事件,而只是将其添加到事件堆栈中。如果不知道如何添加/附加事件,则需要查找如何添加/附加事件。

    注意:您可以使用SOAP或REST来进行日志记录,而不是使用日志脚本。

        4
  •  1
  •   Sphvn Frebin Francis    14 年前

    当脚本在页面上运行时,您可以创建一个警报(弹出菜单),让您知道它在当前所在的页面上:

    alert('Im in your page being your s.js file');
    
        5
  •  1
  •   Chris Laplante    14 年前

    JavaScript必须包含在要执行的页面中。为了 ,您可以使用以下方法获取页面:

    document.write(location.href);
    

    在生产环境中,将位置存储在变量中。

    var loc = location.href;