Programmatically click link in iframe with Javascript

点点圈 提交于 2019-12-12 12:26:12

问题


Here's my html/javascript. Below there are two if statements that I've tried. I used indexof to get the text between the <a></a> tags. Also tried href == to use the href= contents. Both do not work.

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>pb</title>
    <script type="text/javascript">
      function call() {
        alert("Called!");
        var allAnc = document.getElementById("d").contentDocument.getElementsByTagName("a");
        for (var i = 0; i < allAnc.length; i++) {
            if (allAnc[i].href.indexOf("Flag") > 0) {
                alert("Found link by indexof, Trying to click!");
                (allAnc[i]).click();
                break;
            }
            if (allAnc[i].href == "javascript:flag.closeit()") {
                alert("Found link by href, Trying to click!");
                (allAnc[i]).click();
                break;
            }
        }
      }
    </script>
  </head>
  <body>
    <input id="Button1" type="button" onclick="call()" value="button" />
    <iframe id="d" src="sourceurl.html" width="100%" height=700"></iframe>
  </body>
</html>

Here is the link inside the iframe I am trying to click:

<a style="text-align: left;" href="javascript:flag.closeit()" title="Flag">Flag</a>

回答1:


From your comment, you are loading the content of different domain into you iframe, so you just can't read the content of that domain due to same origin policy restrictions.




回答2:


Here's a demo of the issue, code mostly copied & pasted from your question:

http://jsfiddle.net/colllin/G2BDb/

And the inner iframe code is here:

http://jsfiddle.net/colllin/wc8Up/

As you can see in the console when you click the button,

Refused to display 'https://www.google.com/#Flag' in a frame because
    it set 'X-Frame-Options' to 'SAMEORIGIN'.

So it looks like if you have control over the page that the iframe is linking to, you could set X-Frame-Options header on that page to be specify an ALLOW-FROM uri (from MDN):

ALLOW-FROM uri
  The page can only be displayed in a frame on the specified origin.

Alternatively if you have control over the original iframe source (which I assume you do, otherwise it's impossible to even access the contents, let alone click a link), you could add the target="_top" attribute to the link before clicking it. This would cause the linked page to replace your top-level page in the window.

Demo here: http://jsfiddle.net/colllin/G2BDb/2/



来源:https://stackoverflow.com/questions/21193078/programmatically-click-link-in-iframe-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!