0

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

user888734
  • 3,797
  • 5
  • 36
  • 67
  • I doubt it: you can certainly get iframe selections from the containing page. Does clicking the bookmarklet visibly destroy the selection? – Tim Down Aug 10 '12 at 09:39
  • Nope, selection stays... – user888734 Aug 10 '12 at 09:41
  • `http://cases.iclr.co.uk/Subscr/search.aspx?path=../../\0` If you trying to make something like this, forget it! Just an advise.. – Kerem Aug 10 '12 at 11:20
  • http://stackoverflow.com/questions/1471759/how-to-get-selected-text-from-iframe-with-javascript – DG. Aug 10 '12 at 11:47

0 Answers0