【问题标题】:insert window.location.href in iframe src in vanilla在原版的 iframe src 中插入 window.location.href
【发布时间】:2022-01-20 04:02:22
【问题描述】:

我试图弄清楚如何将当前页面 url 插入到已加载但隐藏在同一页面上的 iframe src 中。由于其他功能,我不想使用jQuery。

如您所见,我正在尝试将其复制到 iframe sn-p 中。

任何帮助将不胜感激,谢谢!

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script rel="stylesheet" src="./src/styles.css"></script>
  </head>

  <body>
    <p id="p1" class="offscreen" aria-hidden="true">
      <iframe
        id="card"
        src="http://window.location.href" 
        width="20%"
        height="80%"
        frameborder="0"
      >
      </iframe>
    </p>
    <p id="p2">P2: I am a second paragraph</p>
    <button onclick="copyToClipboard('p1')">Copy P1</button>
    <button onclick="copyToClipboard('p2')">Copy P2</button>
    <br /><br /><input type="text" placeholder="Paste here for test" />

    <!-- <script language="JavaScript">
      var iframe = document.getElementById("card").src;
      iframe.write(window.location.href);
    </script> -->

    <script language="JavaScript">
      function copyToClipboard(elementId) {
        var aux = document.createElement("input");
        aux.setAttribute("value", document.getElementById(elementId).innerHTML);
        document.body.appendChild(aux);
        aux.select();
        document.execCommand("copy");
        document.body.removeChild(aux);
      }
    </script>
  </body>
</html>

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

    只需在 &lt;script&gt; 中分配 URL:

    if(window.top == window.self) {
      // otherwise you end up in infinite nested iframes
      const iframe = document.getElementById('card');
      iframe.src = window.location.href;
    }
    

    【讨论】:

    • 可能需要检查当前窗口是否是顶部窗口,或者最终会出现无限嵌套的 iframe
    • 是的,好点子!
    • 谢谢,不知道为什么我不试试!
    猜你喜欢
    • 2021-04-12
    • 2013-07-04
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多