2015-06-20 55 views
2

當用戶選擇不同來源的iframe中的文本時,由於跨源安全策略,在包含文檔中運行的JavaScript調用window.getSelection()將返回一個None選擇對象。由於用戶沒有選擇整個文檔中的任何內容,而不是返回None,因爲用戶選擇了不同的內容中的某些內容,起源iframe,但它是禁止我的代碼。選擇對象和跨源iframe?

我希望能夠區分這些情況,以便我可以向用戶顯示不同的錯誤消息。這可能嗎?

var sel = window.getSelection(); 
if (sel && sel.type == 'None') { 
    // Did the user not select anything in the entire document? 
    // Or did the user select something in a different origin 
    // iframe that I can't see? 
    // If I could tell the difference between these two cases, 
    // I could show my user a much better error message 
    alert('sel type = None, dunno what it means exactly, kthxbai'); 
} 

完整的演示代碼是在這裏:http://jsfiddle.net/t3bd6zy4/2/

注:這需要任意網站工作,所以改變原產地政策或做使用於PostMessage的東西()不是我一個可行的方法。此外,此代碼只能在最近的Chrome瀏覽器中運行。

更新:我有一個解決這個問題的辦法,儘管只有在Chrome擴展中才有效。

儘管我無法從DOM中獲取不同來源的selectedText而不更改原始策略,但Chrome API會讓您獲取選定的文本,即使它來自不同來源的iframe。 (如果您想了解更多信息,請參閱contextMenus API示例:https://developer.chrome.com/extensions/contextMenus。)

使用此方法意味着我不需要針對空選擇顯示特定於iframe的消息。我的用戶更少的錯誤消息:太棒了。

+0

我非常懷疑你可以。但是,嘿,值得問。 –

回答

1

此作品(jsfiddle):

var iframeClicked = false; 

document.body.addEventListener('mouseup', iframe(false)); 

function iframe(bool) { 
    return function(e) { 
     iframeClicked = bool; 
     //console.log(iframeClicked); 
    } 
} 

focus(); 
var listener = addEventListener('blur', function() { 
    if(document.activeElement === document.getElementsByTagName('iframe')[0]) { 
     iframe(true)(); 
    } 

    removeEventListener(listener); 
}); 

document.getElementById('selbutton').addEventListener('mousedown', function() { 
    var sel = window.getSelection(); 

    if (!iframeClicked) { 
     console.log("selection type of " + sel.type + " value is :" + sel + ":"); 
    } else { 
     console.log("did not get a selection object back from getSelection"); 
    } 
}); 

的解決方案,以檢查是否iframe點擊畫面可以發現in this answer。我們正在尋找的是查看iframe是否是被點擊的最後一件事(因爲如您所知,如果您選擇了某項內容,那麼您點擊的下一件事物將取消選擇該選擇......所以如果iframe是最後一件事點擊,然後我們點擊「獲取選擇」按鈕,然後我們會知道我們試圖在iframe中選擇一些內容。)這很讓人困惑。

反正iframeClicked === true意味着前的最後一件事點擊「獲取選擇」按鈕,用戶點擊確實是iframe。否則,它在以外的地方iframe

+1

是的,的確,這確實奏效!哇,我以爲這真的無法解決;很好地完成(並接受)! – Polly

+0

@Polly,太棒了!很高興它對你有效。 –