How to get value from a link that is inside an iframe

3
   <div id="dinamico" class="row">
     <div class="col-12">
       <iframe class="test" src="https://www.navexterno.com" min-height="70px" width="100%" frameborder="none"></iframe>
     </div>
  </div>

This iFrame contains a menu with 2 links, within the tags nav , ul , li are my links, which are:

<a id="enlace1" href="google.com">Google</a>
<a id="enlace2" href="youtube.com">Youtube</a>

And in my place where the iFrame is placed, I have these links

<a id="enlace-dinamico1" href="#">Google</a>
<a id="enlace-dinamico2" href="#">Youtube</a>

Now I would like to know how I can get the links 1 and 2 (href) that are inside the iframe and assign them to the dynamic links 1 and 2 that are in the static site.

I tried :

var enlace-d = $("#enlace1").attr("href");

Also try :

var anchor = document.getElementById("enlace1");
var href_val = anchor.getAttribute("href");

And also do not select the link.

Help image:

    
asked by Marco Mireles 24.08.2018 в 18:12
source

4 answers

0

Try this way, to get the values of all a pressed,

$(document).ready(function() {
            $("a").click(function(event) {
              var href = $(this).attr('href');
              alert('valor del href' + href);

          });

        });

I hope you serve

    
answered by 24.08.2018 в 18:50
0

In the load event, of your IFrame, you should check its content, between that content, the a

html

<iframe id="myFrame1" class="test" src="https://www.navexterno.com" min-height="70px" width="100%" frameborder="none"></iframe>

js

$(document).ready(function() {
        $('#myFrame1').on('load', function() {
                var elementA = $(this).contents().find("#enlace1").attr('href');
                alert(elementA);
            });
    });
    
answered by 24.08.2018 в 18:26
0

As I supposed, if it's not the same domain, it will not let you

var iFrame = document.getElementById("elframe");


iFrame.addEventListener("load", function() {
    var enlaces = iFrame.contentWindow.document.body.querySelectorAll('a');

    console.log(enlaces);
  });
iframe {
  margin: 5px;
  padding: 0;
  border: 1px solid #ccc;
  width: 320px;
  height: 340px;
}
<iframe id="elframe" src="https://en.m.wikipedia.org/wiki/HTML_element#Frames"></iframe>
    
answered by 24.08.2018 в 21:01
0
var iframe = document.getElementById('iframeId');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

The variable innerDoc will contain the content of the iframe so you can use a selector to get all the links, eg

innerDoc.getElementsByClassName('links')

Assuming that all the links in that iframe have the link class

    
answered by 10.10.2018 в 20:44