Почему мое расширение Chrome работает только тогда, когда я осматриваю всплывающее окно?Javascript

Форум по Javascript
Ответить
Anonymous
 Почему мое расширение Chrome работает только тогда, когда я осматриваю всплывающее окно?

Сообщение Anonymous »

В настоящее время я пишу расширение Chrome, используя JavaScript, который теоретически должен работать в фоновом режиме, но у меня возникают проблемы с ним. Я хотел создать расширение, чтобы помочь мне сосредоточиться, так как я легко отвлекаюсь. Поэтому я настроил систему, в которой любой пользователь может ввести любой URL -адрес, и он займет это значение и добавит ее в список запрещенных URL -адресов, который хранится локально с использованием Chrome.storage . Затем, когда обновляется вкладка, которая измеряется с использованием chrome.tabs.onupdated , она проверяет URL -адрес каждой вкладки, если URL находится в наборе запрещенных URL -адресов, вкладка закрывается. Полный скрипт < /p>

Код: Выделить всё

document.addEventListener('DOMContentLoaded', () => {
/* URL Data from the extension UI (HTML file) */
/* -> InterfaceType: Buttons */
const confirmAddButton = document.getElementById("confirmAddButton"); // Confirm add url from 'urlToAdd' textbox
const confirmRemoveButton = document.getElementById("confirmRemoveButton"); // Confirm remove url from 'urlToRemove' textbox
/* -> InterfaceType: Textboxes */
const urlToAdd = document.getElementById("urlToAdd"); // User inputted url to be added to the list of banned urls.
const urlToRemove = document.getElementById("urlToRemove"); // User inputted url to be added to the list of banned urls.

/* Clear Everything from a particular storage key */
/* -> InterfaceType: Buttons*/
const clearAllUrls = document.getElementById("clearAllUrls"); // Removes all data from the storage key 'urlKey'

/* Display*/
const display = document.getElementById("display"); // The display

// When confirmAddButton is clicked:
confirmAddButton.addEventListener('click', () => {
// Get all data from 'urlKey' storage
chrome.storage.local.get(['urlKey']).then((result) => {
let bannedUrlsList = result.urlKey // Assign result to temporary list
// Checks to see if the urlToAdd is already in the list of bannedUrls &0>
if (bannedUrlsList.includes(urlToAdd.value) == false) { // >&0: If it is not, add it to the list
bannedUrlsList = bannedUrlsList.concat(urlToAdd.value) // Add urlToAdd.value to the temporary list
// set the 'urlKey' storage to the temporary list which has the added url in it
chrome.storage.local.set({'urlKey': bannedUrlsList}).then(() => {
display.innerHTML = `${urlToAdd.value} was added to the list of banned urls`
})
} else { // >&0: Else, alert the user that the url is already in the list
display.innerHTML = `${urlToAdd.value} is already in the list`
}
})
});

// When clearAllUrls is clicked:
clearAllUrls.addEventListener('click', () => {
chrome.storage.local.set({'urlKey': []}).then(() => {
display.innerHTML = `The list of banned urls has been completely wiped`
})
});

// Function checks all tabs to make sure they aren't banned, closes them if they are
function isValidTab() {
// Get all the open tabs from chrome
chrome.tabs.query({windowId: chrome.windows.WINDOW_ID_CURRENT}, (tabs) => {
for (let i = 0 /*i starts at zero*/; i < tabs.length /*i must be less than the numbe of tabs*/; i++ /*increments by one each iteration*/) {
const currentTabUrl = tabs[i].url; //For each tab, assign the tabs URL to a value 'currentTabUrl'
// Get the list of banned URLs from the 'urlKey' storage
chrome.storage.local.get(['urlKey']).then((result) => {
let bannedUrlsList = result.urlKey // Assign result to temporary list
// If the list of banned urls contains the url of the current tab, close the tab, else, leave it be
if (bannedUrlsList.includes(currentTabUrl)) {
chrome.tabs.remove(tabs[i].id) // Closes the current tab
display.innerHTML = `${currentTabUrl} was closed`
} else {
_ = 1 // Do nothing
}
})
}
})
};

// Every time a tab is updated or changed, or a new tab is created, close all banned tabs
chrome.tabs.onUpdated.addListener(() => {
isValidTab()
});
});
< /code>
Это все хорошо и хорошо, но по какой -то причине этот код работает только тогда, когда консоль открыта. Например, допустим, я добавляю URL https://www.dervative-calculator.net/ в список запрещенных URL-списка. Если бы я теперь открыл этот веб -сайт, ничего бы не произошло, перезагрузка ничего не делает, как будто расширение не было. Однако, если я осмотрю расширение и перезагружаю вкладку, и консоль немедленно закрываются. Это не то, что я хочу произойти, расширение должно работать без консоли, которая должна быть открыта. Я установил код в качестве работника службы в файле manifest.json 
, и все разрешения для API Chrome находятся в Manifest.json .
{
"permissions": [
"tabs",
"storage"
],
"background": [
"service_worker": "Code.js"
]
}
< /code>
Если расширение вообще не сработало, это просто означало бы, что мой код не работает, но мой код работает, когда консоль открыта, и только когда он открыт. Я понятия не имею, что вызывает это, так что любая помощь ценится.

Подробнее здесь: https://stackoverflow.com/questions/795 ... -the-popup
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»