How can I get the entered javascript code executed in local area in iframe?

I have an html document loaded in an iframe.
I developed javascript popup menu code for this document, and I am inserting code in an iframe from the main document.

But my code does not work in an iframe because it uses a " document " object, and this surprisingly applies to the main document, not the iframe document.

I also play around content selection, and I need window.getSelection() , which returns to the main documents, and I need window.frames[0].getSelection() .

Am I doing it wrong?
Is there a simple solution to overcome this?

UPDATE: (lightening)
As Bergi pointed out, my question is how to run the javascript code I entered correctly to get the local region, not the global region in the iframe?
Therefore, I do not need to rewrite document and window in the code ...

UPDATE: (skeleton of my html)

 <html> <head></head> <!-- script launches on jquery $(document).ready --> <body> <iframe> [ <body> ... <script></script> <!-- code injected here from the code (appended to the body) --> </body> ] </iframe> </body> </html> 

The script looks like this (using jquery):

 $(function(){ $('iframe').load(function(){ var $doc = $('iframe').contents(); var $head = $('head', $doc); $head.append('<link rel="stylesheet" href="/stylesheets/book-popup-menu.css" />'); var $body = $('body', $doc); $body.append(' \ <div id="popup"> \ </div> \ '); $body.append(' \ <script type="text/javascript"> \ console.log(document.body);// it still displays the global body \ </script> \ '); }); }); 

UPDATE : Violin showing a problem

+4
source share
1 answer

Finally, I found the answer!

If you add code with jQuery, for example $body.append('<script>') , then the '' element is created by document.createElement('script') , so it will be part of the global document. Even after it is inserted into the iframe document, it will execute in the global namespace .

So, the solution - using this fabulous solution :( Putting Javascript in an iframe ) - return to vanilla javascript:

 $('iframe').load(function(){ var $doc = $('iframe').contents(); var $head = $('head', $doc); $head.append('<link rel="stylesheet" href="/stylesheets/book-popup-menu.css" />'); var $body = $('body', $doc); $body.append('<div id="popup"></div>');// non-javascript content works fine var doc = $('iframe').contents()[0]; // doc = $doc[0] does not work for some reason... var script = doc.createElement("script"); script.setAttribute("type", "text/javascript"); script.textContent = "console.log(document.body)"; // this will be iframe body $body[0].appendChild(script1); // $body.append(...) does not work }); 
+2
source

Source: https://habr.com/ru/post/1479543/


All Articles