将iframe-src从一个html页面传递到另一个页面

pass iframe src from one html page to another

本文关键字:另一个 html 一个 iframe-src      更新时间:2023-09-26

我有两个html网页。其中一个页面有一个名为"iframe-content"的"div"。当我点击div时,它应该在第二个html页面中设置iframe-src。

第1页:

<div class="iframe-content" onclick="passIframe()">
     //div which should set the iframe src on the other page on clicking
</div>

第2页:

<iframe src="about:blank" id="native-iframe" width="450" height="180"scrolling="no">
      //The iframe which should obtain the source from the first page 
</iframe>

每当我点击"iframe内容"时,它应该会打开html页面2,并且还应该根据我的意愿设置"本地iframe"源。

有什么有效的方法吗?

您可以将url作为查询参数发送,在page2上,您可以读取并将其设置为iframe。类似这样的东西:

// Page1:
function passIframe() {
    var url = ""; // The url to pass
    window.location.href = "/page2.html?url=" + url;
}
// Page2:
function getParameterByName(name) {
    name = name.replace(/['[]/, "''[").replace(/[']]/, "'']");
    var regex = new RegExp("[''?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/'+/g, " "));
}
var src= getParameterByName("url");
$("iframe").attr("src", url);

注意:getParameterByName只是一个从URL中获取查询字符串参数的函数。我从这个堆栈溢出问题中复制了这个函数,但还有许多其他解决方案可以完成这项任务。

YOu可以将iframe-src属性设置为所需的url

$('iframe').attr('src', url)