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.

小书签链接如下所示:

<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>

而且bookmarklet.js 看起来像:

(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());  
            });
        }
    })();
}

})();

我测试了一些东西——我绝对可以得到框架对象,并返回它的 html,但 getSelection 只是返回空。

它是跨域的吗,因为我的 bookmarklet.js 在其他地方?

更新:作为参考,我专门尝试的页面是这个: http ://cases.iclr.co.uk/Subscr/search.aspx?path=WLR%20Dailys/WLRD%202011/wlrd2012-246

4

0 回答 0