gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:19:36 24 4
gpt4 key购买 nike

许多网页可以使用外部 JavaScript。如何知道哪个网页正在使用外部js脚本?例如,我有一个 javascript 脚本 s.js。 s.js 的函数是否可以检查哪个页面正在使用 s.js?

最佳答案

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

EDIT Now, to answer the question that you actually meant to ask and that is how to track which pages are using your javascript file. I think (and I haven't implemented something like this before) is to use the same strategy as what the analytics sites use.

They all seem to use a variation of a tracking pixel where the browser downloads a script file (e.g. QuantServer - http://edge.quantserve.com/quant.js). The script then requests a 1x1 pixel from the google server and encodes the URL of the webpage into the address of the image. So for stackoverflow.com, the pixel URL is:

http://pixel.quantserve.com/pixel;r=3547206;fpan=0;fpa=P0-82955756-1264139666260;ns=0;url=http%3A%2F%2Fstackoverflow.com.... (I didn't reveal the address as it my browser sends it as I don't really know what it reveals about me :) ).

As you can see, the site's url is a part of the image url. On the server side you would need to have a handler that serves this image and logs the page address by extracting it from the image URL.

The reason for why this is an image and not an AJAX request is because AJAX requests are subject to browser XSS restrictions. Basically, a browser will not make an AJAX call to a website that is not the one serving the page. This means that a page on www.otherpeopleswebsite.com is not allowed to make an AJAX call to www.mywebsite.com. There is no such restrictions on images (or javascript files for that matter).

So a simple system for implementing something like this would do something to this effect:

//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 处理程序将提供 1x1px 图像,将内容类型设置为适当的值(即 image/gif),提取查询字符串并记录 URL。根据您的服务器技术,有多种方法可以实现这一点。

关于javascript - 如何知道哪个网页正在调用外部 javascript 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3242657/

24 4 0
文章推荐: javascript - 当表单与ajax提交事件一起使用时,为什么通常使用
而不是
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com