[英]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,因為:
w.host !=='http://originaldomaine.com'
始終為TRUE
,因為location.host
不包含協議( http(s)://
)。
而且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.