Programatically click link in iframe with Javascri

2019-07-21 09:13发布

问题:

Here's my html/javascript. Below there are two if statements that I've tried. I used indexof to get the text between the 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/