简体   繁体   中英

JS: change inside iframe link tags

I'm trying to change the href attribute of all the a tags inside an iframe from outside of the iframe.

Here is what I have so far:

<Html>
<Head>
    <Title>change links</Title>
</Head>
<body>
    <iframe style="width:100%;height: 100%;border:0;" id="tab" src="http://www.anyside.co.il" ></iframe>
    <script type="text/javascript">
        var frame = document.getElementById("tab");   
        var tags = frame.getElementsByTagName("a");   
        for (var i = 0; i < tags.length; i++) {   
            tags[i].href = 'javascript:alert("")';  
        } 
</script>
</body>
</Html>

What is wrong in this code that it doesn't work?

firstly it have to be the same domain

secondly it should be :

        var frame = window.frames["tab"].document;
    var tags = frame.getElementsByTagName("a");   
    for (var i = 0; i < tags.length; i++) {   
        tags[i].href = 'javascript:alert("")';  
    } 

or :

var frame = document.getElementById("tab").contentDocument;   
    var tags = frame.getElementsByTagName("a");   
    for (var i = 0; i < tags.length; i++) {   
        tags[i].href = 'javascript:alert("")';  
    }

( in your code you only have the iframe tag, but you need the document of the frame of this tag )

and thirdly you should either execute the code when iframe is loaded ( see the event onload of the iframe ), or use a setTimeout with a timeout enough big for any connection speed.

Edit :

In the comments it seems it's more about being on different domain, if it's the case you can't use javascript or frame to access or modify content accross domain.

If it's a static page, just host it yourself, if it's dynamic and it's okay getting a proxy copy of the page, you could use several way :

  1. use a server side language ( like php ) on the same server to get and display the page, then use this page on the same server in the iframe ( then you will be able to have access to it )
  2. yql could be a way too it can get a web page with javascript

Well it's hard to say not knowing what you want to do, maybe the owner of the website could do something, or for example if you just want to add tips on the website for your users making them install an user script wich will execute on the website could be a better way, without knowing why you need this and what's the situation, it's hard to say.

由于安全限制,您的JS代码无法从iframe访问DOM元素(iframe元素位于不同的域中)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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