首页 > 解决方案 > 如何使用 javascript 在站点中的所有页面/内部链接之间传递 URL 参数?

问题描述

我有一个有两个页面的网站,index.html并且page2.html

索引.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 时,为了启用跟踪广告,将以下参数附加到 URL 的末尾:

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

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

非常感谢所有帮助。

标签: javascripthtmlcssurl

解决方案


用于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;
});

编辑

以下是如何使上述内容仅适用于内部链接(我将内部链接分类为以 a/.(相对链接)开头或以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;
                }
            });

推荐阅读