2013-09-22 33 views
1

我目前使用Tampermonkey下面的腳本在谷歌瀏覽器:爲什麼這個腳本不能連續點擊頁面?

// ==UserScript== 
// @name  Youtube opt in Ads per channel 
// @namespace schippi 
// @include  http://www.youtube.com/watch* 
// @version  1 
// ==/UserScript== 

var u = window.location.href; 
if (u.search("user=") == -1) { 
    var cont = document.getElementById("watch7-user-header").innerHTML; 
    var user=cont.replace(/.+\/user\//i,'').replace(/\?(?:.|\s)*/m,''); 
    window.location.href = u+"&user="+user; 
} 

它似乎在Firefox中的Greasemonkey,但在谷歌瀏覽器很好地工作,它似乎只適用於第一個點擊一個YouTube視頻。

更具體地說,如果我點擊一個YouTube視頻:
youtube.com/watch?v=MijmeoH9LT4
它重定向我:
youtube.com/watch?v=MijmeoH9LT4&user=Computerphile

但是,如果我點擊從相關視頻豎線的視頻,它不似乎沒有做進一步的重定向。

+0

@BrockAdams:嗯..似乎仍然無法正常工作。新腳本:http://pastie.org/pastes/8347656/text – user2805335

+0

是的,這是相同的問題,但是因爲YouTube不再激發'hashchange'事件,所以解決方案並不完全相同。我會稍微發表一個答案。 –

回答

2

唉,在Chrome中仍然沒有真正「乾淨」的方式來做到這一點。 (Firefox有更多的選擇。)

最好的辦法就是輪詢location.search;見下文。

其他選擇在Chrome中,目前,不建議使用 - 但在這裏,他們是參考:

  • Hack into the history.pushState function。這可以提供更快的頁面更改通知,但在運行代碼之前觸發,所以它仍然需要定時器。另外,它在用戶標記環境中引入了跨範圍的問題。
  • 使用突變觀察者來監視對<title>標記的更改。這可能工作正常,但可能會在您想要之後觸發,導致延遲併發出「閃爍」。也可能不適用於設計不佳的頁面(YouTube可以)。


還要注意的是replace()語句,從這個問題,將炸燬的URL和404腳本在幾起案件。使用DOM方法獲取用戶(見下文)。


投票代碼(簡單,健壯,跨瀏覽器):

// ==UserScript== 
// @name  Youtube opt in Ads per channel 
// @namespace schippi 
// @include  http://www.youtube.com/watch* 
// @version  1 
// @grant  GM_addStyle 
// ==/UserScript== 
/*- The @grant directive is needed to work around a design change 
    introduced in GM 1.0. It restores the sandbox. 
*/ 
var elemCheckTimer  = null; 
var pageURLCheckTimer = setInterval (
    function() { 
     if (this.lastQueryStr !== location.search) { 
      this.lastQueryStr = location.search; 
      gmMain(); 
     } 
    } 
    , 111 //-- Nine times a second. Plenty fast w/o bogging page 
); 

function gmMain() { 
    if (! /user=/.test (window.location.href)) { 
     elemCheckTimer = setInterval (checkUserAndRelocate, 24); 
    } 
} 

function checkUserAndRelocate() { 
    var elem  = document.querySelector (
     "#watch7-user-header a[href*='/user/']" 
    ); 
    if (elem) { 
     clearInterval (elemCheckTimer); 
     var user = elem.href.match (/\/user\/(\w+)\W?/); 
     if (user && user.length > 1) { 
      location.replace (location.href + "&user=" + user[1]); 
     } 
    } 
} 
+0

該腳本可能已過時。它將用戶放在主頁上,如果你點擊它。它不會在沒有重新加載的情況下將其放入視頻中。 – Gopoi

+0

@Gopoi,是的,YouTube變化很快。我會把它放在隊列中重新檢查,但這個問題似乎是低利率的 - 所以它的優先級低。 –

+0

我自己檢查一下,看看我能否修復。這只是奇怪的腳本似乎不開始時,在/觀看頁面,但它會在重新加載後。可能是一個篡改密鑰問題?另外,當退出一個頁面(按下YouTube的主頁按鈕)時,用戶=卡在導致錯誤的地址中。我嘗試了第一個腳本,並更改​​了第二個替換爲/\"(?:.|\s)*/m匹配終止「,但腳本不執行。在調試窗口中,它顯示腳本已排隊,但從不執行它。 – Gopoi

相關問題