2016-08-21 14 views
1

(這是一個轉發,從以前我沒有適當的代碼示例)如何使用jQuery觸發Facebook'New Message'按鈕?

我一直在我的智慧結束試圖找出如何與Facebook的前端UI進行交互。

我正在寫一個簡單的Firefox插件,當它識別出你正在使用的時候,它只是運行一些JavaScript/jQuery https://www.facebook.com/ - 純粹是爲了保持自己的工作效率,而且當我在Facebook上時不會分心。

但無論如何,我一直試圖簡單地選擇聊天邊欄右下角的「新消息」按鈕。沒有事件 - 重點,點擊,按下'Enter',進入該按鈕的href等等 - 至今仍然有效。這就是字面意思,我只想打開一個新的消息框,我的插件就完成了。但由於某種原因,無論Facebook的UI在幕後發生了什麼黑魔法,該死的按鈕都不會按下!

有沒有人有什麼想法做什麼?

以下是我在我的劇本已經試過例子:

試圖聚焦元素後點擊:

$('[data-tooltip-content="New Message"]').focus(); 
$('[data-tooltip-content="New Message"]').trigger('click'); 

窗口位置設置爲在href - 所有做「#」被追加到URL:

var href = $('[data-tooltip-content="New Message"]').attr('href'); 
window.location.href = href; 

試圖使它看起來像我聚焦元素後按「確認」鍵:

$('[data-tooltip-content="New Message"]').focus(); 
var f = jQuery.Event("keypress"); 
f.which = 13; 
f.keyCode = 13; 
$('[data-tooltip-content="New Message"]').trigger(f); 

混合兩者 '點擊' 和 '輸入' 方法:

$('[data-tooltip-content="New Message"]').focus(); 
$('[data-tooltip-content="New Message"]').trigger('click'); 
var f = jQuery.Event("keypress"); 
f.which = 13; 
f.keyCode = 13; 
$('[data-tooltip-content="New Message"]').trigger(f); 

我甚至使用的標識符像$('a#js_g') Firebug的檢查後。

在此之前,我嘗試打開消息框的複雜方法涉及到實際上在聊天搜索框中進行搜索,然後等待結果顯示出來,然後再選擇並單擊突出顯示的個人(如果有的話)在結果中。問題是,搜索框從來沒有註冊我的輸入,我猜想它是「自然的用戶輸入」,所以即使使用keyup()事件,更改輸入框的值也不會觸發相關結果的搜索2秒,輸入框的值剛剛清除。

它繼續是這樣的:

var searchChat = "something to search"; 
$('input._58al').focus(); 
$('input._58al').val(searchChat).keyup(); 
var e = jQuery.Event("keypress"); 
e.which = 13; //choose the one you want 
e.keyCode = 13; 
$("input._58al").trigger(e); 
$('input._58al').focus(); 
$("input._58al").trigger(e); 

//I set a timeout here, by encapsulating the following in a function, to wait for the results to show up 

var header = $('div._225b').text(); 
var listItems = $('ul#js_3 li'); 
var selected = false 
listItems.each(function(index, li) {//Basically, go down all the list of items and see if any of them are auto-selected; we just open that one, as facebook's default choice 
    if ($(li).attr("aria-selected")) { 
     $(li).trigger('click'); 
     selected=true; 
    } 
}); 

我讀的地方,它可能是一個跨來源的問題,與我的Firefox內容腳本被阻止?但即使在更改我的包中的權限之後。JSON,什麼都沒有發生:

"permissions": { 
    "cross-domain-content": ["https://www.facebook.com/"] 
} 
+1

感謝您付出努力寫出比您最初的問題更好的問題。另一次,處理原始問題的「正確」方式是編輯它。如果你有(如果那個被編輯爲這個內容),我會收回我的投票結束,刪除我的倒票和刪除一些評論,要求更多的信息。我可能會投票(就像我在這裏)。另一方面,很多人會觀看新的問題信息,特別是流行的標籤,如果出現質量問題,那麼最初的問題會導致更好的反應。 – Makyen

回答

1

看起來你無法在Facebook上的頁面使用jQuery,所以你必須使用香草JS

document.querySelectorAll('[data-tooltip-content="New Message"]')[0].click()

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll


之所以jQuery不適用於Facebook頁面: https://stackoverflow.com/a/20286152/5811984

+0

哦,我的上帝,我不敢相信這工作!謝謝! –

+0

爲什麼Facebook不允許使用jQuery? –

+0

@vawd_gandi我更新了我的答案和更多細節。 – Minderov