[英]change src of <iframe> with javascript
What I would try is to change src="url"
via JavaScript inside the iframe but seems didn't work 我想尝试的是通过iframe内的JavaScript更改src="url"
,但似乎不起作用
the iframe 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 code 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';
}
The purpose is if the the domain doesn't match the original, the js code will call id="cta"
to replace it with the site2 目的是如果域与原始域不匹配,则js代码将调用id="cta"
将其替换为site2
Try this one: 试试这个:
var loc = 'http://site2.com/59870';
document.getElementById('sorror').src = loc;
HTML (it needed a small syntax fix) 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 JS
var frame = document.getElementById('sorror');
frame.src = "http://site2.com"
You can either use loc.host
on left and without http://
on right side (or) combine it with loc.protocol
as below. 您可以在左侧使用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';
}
but seems didn't work. 但似乎没有用。
I guess that you mean your iframe src
always chaging to site2 because: 我想你是说你的iframe src
总是赶到site2,因为:
w.host !=='http://originaldomaine.com'
always TRUE
, because location.host
doesn't include protocol ( http(s)://
). w.host !=='http://originaldomaine.com'
始终为TRUE
,因为location.host
不包含协议( http(s)://
)。
Also Math.floor(Math.random() *101) < 100
in almost time will be TRUE
. 而且Math.floor(Math.random() *101) < 100
在几乎时间内也是TRUE
。 because Math.floor(0.99999999999999994 * 101) === 100
. 因为Math.floor(0.99999999999999994 * 101) === 100
。
So your if conditions never be FALSE
and your iframe always changing src
. 因此,如果条件永远不会为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';
}
Extra point: use sandbox
attribute in iframe to disable runninig scripts and avoid redirecting. 重点:在iframe中使用sandbox
属性可禁用runninig脚本并避免重定向。
<iframe src='a.php' sandbox></iframe>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.