【问题标题】:How to Get # URL value with JavaScript如何使用 JavaScript 获取 # URL 值
【发布时间】:2022-08-21 02:07:34
【问题描述】:

我不能在我的 CloudFlare Worker 服务器上使用 url Query https://example.com/?l=http://example2.com

所以,我的问题是,如何将此 JS 脚本转换为使用 https://example.com/#http://example2.com

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }      

var l = getUrlVars()[\"l\"];

根据 jp-jee 的回复,这是我的脚本:

            <script>
var hash = window.location.hash;
    function change(){
        var txt = hash.replace(\"#\", \"\");
        document.getElementById(\"url\").value = txt;
    }
    
     </script>
          
           <input onclick=\"change()\"  name=\"url\" type=\"text\" id=\"url\" placeholder=\"enter url here\" value=\"enter url here\" />
           <button id=\"submit\" onclick=\"submitURL()\">Submit</button>
    

谢谢 :)

  • 你到底想要什么?您是否要从https://example.com/#http://example2.com 中提取http://example2.com
  • 我只想用包含在 #example.com 上的 url 替换占位符 url 文本

标签: javascript url cloudflare cloudflare-workers


【解决方案1】:

使用 window.location.hash 并从结果中删除 # 字符。

对于 URL https://example.com/#http://example2.comwindow.location.hash evauates 到 "#http://example2.com"

【讨论】:

    【解决方案2】:

    # 和它后面的文本称为“片段”或“哈希”。 URL 类将此放在属性 .hash 中。

    但是,有一个不同的问题:此文本不会以常规 HTTP 发送到服务器——它只保存在浏览器中。这意味着您无法在 Cloudflare Workers 或任何其他服务器端代码中看到此值。如果您想使用# 进行导航,您必须在客户端的浏览器中实现您的导航。

    【讨论】:

    • 是的,这就是我的意思。我只想替换客户端表单上的 url 文本值。检查我的问题更新。谢谢
    【解决方案3】:

    由于您使用的是 Cloudflare worker,它的工作方式类似于 nodeJS 或任何其他服务器端应用程序。这意味着您将无权访问 window.*document.* 对象。

    如果您尝试替换占位符,您应该使用.placeholder 而不是.value,您可以使用您的工作人员将此脚本附加到文档的头部或正文中

    <script>
    var hash = window.location.href;
    var txt = hash.replace("#", "");
    document.getElementById("url").placeholder= txt;
    </script>
    

    这样,一旦您的页面加载,浏览器就会执行脚本并修改占位符。

    或者,您也可以使用 Cloudflare worker 来拦截和修改响应,方法是将您的 HTML 模板更改为

    <input onclick="change()"  name="url" type="text" id="url" cloudflare_placeholder="enter url here" value="enter url here" />
    

    现在从您的工作人员那里,您可以将文本替换为

    intercepted_html = intercepted_html.replace('cloudflare_placeholder=\"enter url here\"', 'placeholder=\"${host}/${pathname}\"')
    

    有关如何使用 Cloudflare worker 修改响应的示例。 Cloudflare response modification

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2021-01-22
      • 2014-11-28
      • 2017-08-14
      • 2020-10-07
      • 2012-07-26
      相关资源
      最近更新 更多