I'm trying to make a bookmarklet that does something with the selected text on any given website, but I'm having trouble when the selected text is in an iframe.
The bookmarklet link looks like:
<a id="bookmarklet" href="javascript:(function(){if(window.myBookmarklet!==undefined)
{myBookmarklet();}
else{document.body.appendChild(document.createElement('script')).src='http://www.mywebsite.com/bookmarklet.js?';}})();
">Bookmarklet</a>
And bookmarklet.js looks like:
(function(){
var v = "1.3.2";
if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
var done = false;
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
initBookmarklet();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
} else {
initBookmarklet();
}
function initBookmarklet() {
(window.myBookmarklet = function() {
if($('iframe').length > 0) {
$('iframe').each(function(){
var iframe = $(this).get(0);
var win= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;
alert (win.getSelection().toString());
});
}
})();
}
})();
I tested a few things - I can definitely get the frame object, and return its html, but getSelection just returns empty.
Is it a cross domain thing, because my bookmarklet.js is somewhere else?
UPDATE: For reference, the page I am specifically trying this on is this one: http://cases.iclr.co.uk/Subscr/search.aspx?path=WLR%20Dailies/WLRD%202011/wlrd2012-246