Sergio santa
Sergio santa

Reputation: 1

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

the 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

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

Upvotes: 0

Views: 93

Answers (4)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

but seems didn't work.

I guess that you mean your iframe src always chaging to site2 because:

  1. w.host !=='http://originaldomaine.com' always TRUE, because location.host doesn't include protocol (http(s)://).

  2. Also Math.floor(Math.random() *101) < 100 in almost time will be TRUE. because Math.floor(0.99999999999999994 * 101) === 100.

So your if conditions never be FALSE and your iframe always changing 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 src='a.php' sandbox></iframe>

Upvotes: 0

Aruna
Aruna

Reputation: 12022

You can either use loc.host on left and without http:// on right side (or) combine it with loc.protocol as below.

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

Upvotes: 0

DDan
DDan

Reputation: 8276

HTML (it needed a small syntax fix)

<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"

Upvotes: 1

claudios
claudios

Reputation: 6656

Try this one:

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

Upvotes: 1

Related Questions