将src更改为<iframe>使用javascript

change src of <iframe> with javascript

本文关键字:iframe gt 使用 javascript src lt      更新时间:2023-09-26

我想尝试的是通过iframe中的JavaScript更改src="url",但似乎不起的作用

iframe

<iframe id="cta" src="http://site1.com/37046"  opacity="0" scrolling="no" margin-top="50px" marginwidth="0" marginheight="0" align="middle" frameborder="0" width="100%" height="160px">
</iframe>

JavaScript代码

var w = window.top.location;
if(w.host !=='http://originaldomaine.com' && Math.floor(Math.random() *101) < 100){
   document.getElementById("cta").src = 'http://site2.com/59870';
}

目的是,如果域与原始域不匹配,js代码将调用id="cta",将其替换为site2

试试这个:

var loc = 'http://site2.com/59870';
document.getElementById('sorror').src = loc;

HTML(需要一个小的语法修复(

<iframe src="http://site1.com/37046"  id="sorror" opacity="0" scrolling="no" margin-top"50px" marginwidth="0" marginheight="0" align="middle" frameborder="0" width="100%" height="160px">
</iframe>

JS-

var frame = document.getElementById('sorror');
frame.src = "http://site2.com"

您可以在左侧使用loc.host,在右侧不使用http://(或者(将其与loc.protocol组合,如下所示。

var loc = window.top.location;
if(loc.protocol + '//' + loc.host !== 'http://originaldomaine.com') {
   document.getElementById("cta").src='http://site2.com/59870';
}

但似乎不起作用。

我猜你的意思是你的iframe src总是转向site2,因为:

  1. w.host !=='http://originaldomaine.com'总是TRUE,因为location.host不包括协议(http(s)://(。

  2. 而且CCD_ 11在几乎时间内将是CCD_。因为CCD_ 13。

所以你的if条件永远不是FALSE,你的iframe总是在改变src

    var w = window.top.location;
    if(w.host !== 'originaldomaine.com' && Math.floor(Math.random() *101) < 100){
     document.getElementById("cta").src = 'http://site2.com/59870';
    }

额外的一点:使用iframe中的sandbox属性可以禁用运行脚本并避免重定向。

<iframe src='a.php' sandbox></iframe>