2017-07-17 24 views
1

我正在使用Google Chrome擴展程序,並且遇到了我無法自行解決的錯誤。如何在當前選項卡中停止執行內容腳本?

它將按預期切換到Youtube的暗模式有一個YouTube選項卡上,但如果你在YouTube和按Ctrl/Cmd的點擊一個鏈接(在新標籤頁中打開),content.js再次被觸發和當前標籤變成白色,新標籤變黑。

如果您處於黑色標籤中,「孩子」選項卡會自動變暗。

manifest.json的:

{ 
    "manifest_version": 2, 

    "permissions": [ 
     "https://www.youtube.com/*", 
     "activeTab" 
    ], 

    "background": { 
     "scripts": ["background.js"], 
     "persistant": false 
    }, 

    "browser_action": { 
     "default_title": "Engage Youtube Dark Mode." 
    }, 

    "content_scripts": [ 
    { 
     "matches": ["https://www.youtube.com/*"], 
     "js": ["content.js"] 
    }] 
} 

background.js:

//var alreadyTriggered = false; 

chrome.browserAction.onClicked.addListener(function(tab) { 
    chrome.tabs.executeScript(null, {file: "clicker.js"}); 
}); 
/* 
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { 
    alreadyTriggered = false; 
});*/ 

chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) { 
    //if (!alreadyTriggered) { 
     chrome.tabs.executeScript(null, {file: "clicker.js"}); 
     //alreadyTriggered = true; 
    //}; 
    return true; 
}); 

content.js:

var myDate = new Date(); 

if ((myDate.getHours() <= 7) || (myDate.getHours() >= 19)) 
{ 
    var darkMode = document.body.getAttribute("dark"); 
    if (!darkMode) { 
     chrome.runtime.sendMessage(window.location.href, function(result) {}); 
    }; 
}; 

我猜,我使用activeTab不正確。任何幫助將不勝感激。謝謝!

clicker.js:

stepOne(); 

function stepOne() { 
    try { 
     var buttons = document.querySelectorAll("button.ytd-topbar-menu-button-renderer"); 
     buttons[0].click(); 
     stepTwo(); 
    } 
    catch(error) { 
     setTimeout(stepOne, 250); 
    } 
} 

function stepTwo() { 
    try { 
     buttons = document.querySelectorAll("paper-item.ytd-account-settings"); 
     buttons[0].click(); 
     stepThree(); 
    } 
    catch(error) { 
     setTimeout(stepTwo, 100); 
    } 
} 

function stepThree() { 
    try { 
     buttons = document.querySelectorAll("paper-toggle-button.style-scope.ytd-account-settings"); 
     buttons[0].click(); 

     document.body.click(); 
    } 
    catch(error) { 
     setTimeout(stepThree, 100); 
    } 
} 
+0

@wOxxOm感謝您的評論。我只是更新它來添加content.js – Sam

回答

0

什麼結束了,我的工作是使用的組合: 使用window.onload = doStuff();

,並確保對於darkMode值爲null,不undefined

希望這可以幫助一直在無休止調整代碼的人。

相關問題