如何使用javascript在网站的所有网页/内部链接中传递网址参数?

问题描述 投票:5回答:2

我有一个有两页的网站,index.htmlpage2.html

index.html的:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Homepage</title>    
    <style type="text/css">
      #holder {margin: 20px auto; max-width: 900px;}      
    </style>
  </head>
  <body>
    <div id="holder">
      <h1>Home</h1>
      <ul id="menu">
        <li><a href="/page2.html">Internal Link</a></li>
        <li><a href="https://www.apple.com/" target="_blank">App Store</a> 
   </li>
      </ul>
      <h2 id="useApp">Is the user using our app?</h2>
    </div>
  </body>
</html>

page2.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Page 2</title>    
    <style type="text/css">
      #holder {margin: 20px auto; max-width: 900px;}      
    </style>
  </head>
  <body>
    <div id="holder">
      <h1>Internal Page</h1>
      <ul id="menu">
        <li><a href="/index.html">Homepage</a></li>
        <li><a href="https://www.apple.com/" target="_blank">App Store</a> 
       </li>
      </ul>
      <h2 id="useApp">Is the user using our app?</h2>
    </div>
  </body>
</html>

当用户通过点击Google广告登录index.html时,为了启用跟踪广告,请将以下参数附加到网址末尾:

?utm_source=google&utm_medium=search&utm_campaign=summer19

出现的问题是当用户导航到站点内的另一个页面时,这些URL参数将丢失。我想写一些Javascript,当用户单击内部链接时,会在用户的网站旅程中传递URL参数。在外部链接的情况下,它不能包括这些参数。我怎样才能最有效地实现这一目标?

非常感谢所有帮助。

javascript html css url
2个回答
5
投票

使用querySelectorAll查找具有href属性的所有元素,并附加URL(window.location).search中的搜索字符串:

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
    var current = link.href;
    link.href = current + queryString;
});

EDIT

以下是如何使上述仅适用于内部链接(我将内部链接分类为以/.(相对链接)开头的那些,或者以http开头并包含window.location.hostname(绝对链接):

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
            if (link.href.startsWith("/") || link.href.startsWith(".") || (link.href.startsWith("http") && link.href.include(window.location.hostname)) {
                    var current = link.href;
                    link.href = current + queryString;
                }
            });

0
投票

以下是检查内部或外部链接的方法:

var isExternal = function(url) {
    return !(location.href.replace("http://", "").replace("https://", "").split("/")[0] === url.replace("http://", "").replace("https://", "").split("/")[0]);   
}

这样我们就可以从URL获取参数字符串:

var params = new URL(window.location).search;

最后遍历所有页面链接并过滤内部链接。然后将参数字符串附加到每个内部链接:

document.querySelectorAll("[href]").forEach(li => {
    var current = li.href;
    if(isExternal(current)){
        li.href = current + params;
    }    
});
© www.soinside.com 2019 - 2024. All rights reserved.