繁体   English   中英

更改的src <iframe> 用JavaScript

[英]change src of <iframe> with javascript

我想尝试的是通过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. 而且Math.floor(Math.random() *101) < 100在几乎时间内也是TRUE 因为Math.floor(0.99999999999999994 * 101) === 100

因此,如果条件永远不会为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属性可禁用runninig脚本并避免重定向。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM