same origin policy how to circumvent

Asked

Viewed 47 times

1

I own a site on a certain domain and within that site an Iframe with different port domain and host, but within this Iframe I want to realize a "document.getElementsByClassName('classe')[0].innerText" of a class outside of Iframe, but the error:

"VM2184:1 Uncaught Typeerror: Cannot read Property 'innerText' of Undefined at :1:131"

I believe it is because I am trying to read a data from outside Iframe, I researched several ways to solve but so far I have not found an answer to answer.

Code:

 $(document).ready(function teste() {
            var dados = window.document.getElementsByClassName('classe')[0].innerText
            if (dados != null) {
                document.getElementById('nome').value = dados;
                $.post("/WebAPI/api/funcao", { data: dados });
                reset();
            }
        });

3 answers

0

For those who need to take the main page element and move to a different domain Iframe read the following resolution, after searching thousands of Chinese and Turkish websites I finally found a solution.

On the page you will send the element put the following code

window.parent.frames[0].postMessage( tes, '*');

On the page that will receive the element put the following code

window.addEventListener("message", function(e){
	//faca qualquer coisa aqui como atribuir a uma variável e tal e usar depois, coloque o alert só para ver se o elemento estava chegando e sim ele chegou!
  alert(e.origin + "-" e.data);
},false);

I warn you that I do not know if the method used is safe to prevent other sites from picking up this element you are transferring but, is working.

0

Well, that’s because you’re running the script inside your main page! So there really is no such class in your main page but in iframe, to access the classes/id’s within iframe you need to do this:

document.getElementsByTagName("iframe")[0].ownerDocument.getElementsByTagName("html")[0].getElementsByClassName("exemplo")

I hope I’ve helped!!

  • Is there a reverse path too? type i’m in Iframe running a code to grab an element from the main page?

  • Unlike no! It would be very unsafe! Imagine you put a script on your page that screws with the index of who put the iframe on it!

  • 1

    makes sense kk, thank you very much clarified things here!

  • If I could answer accurately, could I mark it as correct? = D

0


You’re not having a problem with Policy of "same origin", yet.

To try to access the contents of Parent you can use something like parent.document.getElementsByClassName('suaClasse')[0].innerText and then have a problem with CORS because it is not possible to communicate between an iframe and another domain:port.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.