0

I have the following html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Scrape test</title>

    </head>
    <body>
        <div id="beatles">
            <div>
                <iframe id="gozujinsama"></iframe>
            </div>
        </div>
        <script type="text/javascript">
            var ifrm = document.getElementById('gozujinsama');
            var doc = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;
            doc.open();
            doc.write("<DOCTYPE html><html><body><a href=\"http://google.com\"><img src=\"\"/></a></body></html>");
            doc.close();
        </script>
    </body>
</html>

What I try is to simulate how various ad scripts write html content in iframes. But when I try to visit it then I get the following error from my javascript console:

TypeError: doc.write is not a function

Do you have any idea why?

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164

3 Answers3

1

You wrote the code wrong.

var ifrm = document.getElementById('gozujinsama');
var doc = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;

doc.document.open();
doc.document.write("<DOCTYPE html><html><body><a href=\"http://google.com\"><img src=\"\"/></a></body></html>");
doc.document.close();

The ifrm object has a property of document which has the function write. In your code you tried to call the open, write, and close functions on a DOM reference.

More Information

Lars Peterson
  • 1,508
  • 1
  • 10
  • 27
1

Here is working code based on your code.

Jsfiddle

Full working Code

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Scrape test</title>

</head>
<body>
    <div id="beatles">
        <div>
            <iframe id="gozujinsama"></iframe>
        </div>
    </div>
    <script type="text/javascript">
        var ifrm = document.getElementById('gozujinsama');
        var doc = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;
        doc.document.open();
        doc.document.write('<DOCTYPE html><body><a href=\"http://google.com\"><img src=\"\"/></a></body></html>');
        doc.document.close();
    </script>
</body>
</html>
MMRahman
  • 319
  • 4
  • 15
0

An alternative approach is:

var ifrm = document.getElementById('gozujinsama');
var doc = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument;

doc.open();
if(doc.write){
    doc.write("<DOCTYPE html><html><body><a href=\"http://google.com\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/272px-Google_2015_logo.svg.png\"/></a></body></html>");
} else {
   doc.document.write("<DOCTYPE html><html><body><a href=\"http://google.com\"><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/272px-Google_2015_logo.svg.png\"/></a></body></html>");
}

doc.close();
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164