I have a html document loaded in an iframe.
I have developed some popup-menu code in javascript for that document and I inject the code into the iframe from the main document.
But my code does not work in the iframe because it uses the "document
" object and that surprisingly refers to the main document and not the iframe document.
I also play around content selection and there I need window.getSelection()
which goes back to the main document's selections and I'd need window.frames[0].getSelection()
instead.
Am I doing sth wrong?
Is there any simple solution to overcome this?
UPDATE:(clarification)
As Bergi pointed out, my question is about how to run correctly injected javascript code to get local scope and not global scope in the iframe?
So I do not have to rewrite document
's and window
's in the code...
UPDATE: (skeleton of my html)
<html>
<head></head> <!-- script launches on jquery's $(document).ready -->
<body>
<iframe>
[
<body>
...
<script></script> <!-- code injected here from the code (appended to the body) -->
</body>
]
</iframe>
</body>
</html>
The script goes 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: A fiddle demonstrating the issue