Javascript 将单击的(外部)链接记录到Web服务器日志或文件

Javascript 将单击的(外部)链接记录到Web服务器日志或文件,javascript,jquery,html,Javascript,Jquery,Html,我有一个用php编写的网站。我有很多外部链接,比如: <a href="http://example.com" target="_blank"> 我想要的是,如果用户点击这些链接,它应该将其记录在某个地方。首选的是apache日志。如果不可能,则登录一个文件 如何使用(可能使用js)实现这一点?在apache日志中获取它的一个简单解决方案是使用以下内容替换外部链接: 上述的 或者您可以使用jQuery捕获点击事件,并以目标URL作为查询参数向tracker.php文件发出请求

我有一个用php编写的网站。我有很多外部链接,比如:

<a href="http://example.com" target="_blank">

我想要的是,如果用户点击这些链接,它应该将其记录在某个地方。首选的是apache日志。如果不可能,则登录一个文件


如何使用(可能使用js)实现这一点?

在apache日志中获取它的一个简单解决方案是使用以下内容替换外部链接:

上述的


或者您可以使用jQuery捕获点击事件,并以目标URL作为查询参数向
tracker.php
文件发出请求,然后重定向:

<a href="http://example.com" target="_blank">test</a>

// Click event for a tags with target='_blank' attribute
$("a[target='_blank']").click(function(e){
  e.preventDefault(); // Prevent the default behaviour (the link opening)
  var href = $(this).attr("href"); // Get the href attribute of the clicked element

  // Make a get request to tracker.php passing the encoded href
  $.get("tracker.php?url=" + encodeURIComponent(href), function(data) {
    window.open(href); // Open the link in a new window once http request is complete
  });
});

//单击事件以获取具有target=''u blank'属性的标记
$(“a[target=”\u blank'])。单击(函数(e){
e、 preventDefault();//防止默认行为(链接打开)
var href=$(this.attr(“href”);//获取单击元素的href属性
//通过编码的href向tracker.php发出get请求
$.get(“tracker.php?url=“+encodeURIComponent(href),function(data){
window.open(href);//http请求完成后在新窗口中打开链接
});
});
这种方法的缺点是:

  • 不会捕获右键单击+在新选项卡中打开(也不会捕获鼠标中键单击)

  • 在http请求期间,用户将有一点延迟

将捕获键盘控件(焦点+返回键)

要使这两种方法都起作用,您需要确保将apache配置为记录GET请求,默认情况下很可能是这样,例如:

0.0.0.0---[20/Feb/2020:13:15:48+0100]“GET/tracker.php?url=HTTP/1.1”200


对于jquery部分,我创建了这个tracker.php,但它看起来没有被触发:没有以什么方式触发?没有执行tracker.php文件吗?或者文件写入不起作用?它尚未执行。这是我在原始站点中为target=''u blank'属性$(“a[target=''u blank'])的标记添加的内容://单击(函数(e){e.preventDefault();//防止默认行为(打开链接)var href=$(This.attr(“href”);//获取所单击元素的href属性//向tracker.php发出Get请求,传递编码的href$.Get(“tracker.php?url=“+encodeURIComponent(href),function(data){window.open(href);//在http请求完成后在新窗口中打开链接}););对于一些lazyload和Massey js插件,没有什么小错误。
$("a[target='_blank']").each(function(e){
  var href = $(this).attr("href"); 
  $(this).attr("href", "tracker.php?url=" + encodeURIComponent(href)); 
});
<a href="http://example.com" target="_blank">test</a>

// Click event for a tags with target='_blank' attribute
$("a[target='_blank']").click(function(e){
  e.preventDefault(); // Prevent the default behaviour (the link opening)
  var href = $(this).attr("href"); // Get the href attribute of the clicked element

  // Make a get request to tracker.php passing the encoded href
  $.get("tracker.php?url=" + encodeURIComponent(href), function(data) {
    window.open(href); // Open the link in a new window once http request is complete
  });
});