Код не работает потому что, он выполняется в контексте content_scripts
и не имеет доступа к переменным, функциям определенным на странице.
Вот что говорит об этом документация:
Content scripts execute in a special environment called an isolated
world. They have access to the DOM of the page they are injected into,
but not to any JavaScript variables or functions created by the page.
It looks to each content script as if there is no other JavaScript
executing on the page it is running on. The same is true in reverse:
JavaScript running on the page cannot call any functions or access any
variables defined by content scripts.
Для того, чтобы код начал работать в контексте страницы, нужно определить соответствующий ключ в manifest.json
, а именно web_accessible_resources
.
Пример использования этого ключа:
{
"web_accessible_resources": ["js/script.js"]
}
где script.js
- скрипт, который должен выполняться в контексте web
страницы.
Если встраивать скрипт без указания соответствующего ключа, то в консоли web
страницы будет получена ошибка:
Denying load of
chrome-extension://aomgbbmcobgkafcfkedmilgaohcapael/js.js. Resources
must be listed in the web_accessible_resources manifest key in order
to be loaded by pages outside the extension.
Execution environment | Web Accessible Resources
UPD:
проблема в том что я спокойно перехватываю все alert/confirm/prompt
барузерного JS, но именно на regex101.com всёравно выводится окно, как
я понимаю оно другого типа
Это обычное confirm
окно.
Появляется в результате события beforeunload
, т.е перед закрытием страницы, но при условие что свойство returnValue
будет иметь не пустое значение.
When this event returns a non-void value, the user is prompted to
confirm the page unload. In most browsers, the return value of the
event is displayed in this dialog.
Кастомизировать его нельзя, из-за политики безопасности. Некоторые версии браузеров (Firefox
до 44.0, Google Chrome
до 51.0, и т.д) позволяют изменить текст сообщения. В более новых версиях поддержку кастомных сообщений удаляют, заменяя на сообщения, которые определяет браузер.
В данном случае, при попытке уйти с сайта срабатывает вышеупомянутое событие:

А вот код функции обработчика (часть ревалентного кода не скопирована):
window.addEventListener("beforeunload", function (e) {
var t = {
regex: $("#regex").val(),
options: getOptions(),
regexText: $("#regex_string").val(),
isSub: sub_enabled(),
sub: $("#sub").val(),
delimiter: $("#delimiter_selector").text(),
flavor: getFlavor(),
permaid: $("#permalink_menu").attr("data-permalink"),
unitTests: V(!1)
}, a = JSON.stringify(t);
if (a !== X) {
var i = "Your most recent changes have not been saved. ";
return i += "If you leave before saving, your changes will be lost.", (e || window.event).returnValue = i, i
}
});
Убрать обработчик не получится, так как для для этого нужна ссылка на него, а ее нету, так как применена анонимная функция.
Calling addEventListener to an anonymous function creates a new
listener each time. Calling removeEventListener to an anonymous
function has no effect. An anonymous function creates a unique object
each time is is called, it is not a reference to an existing object
though it may call one. When adding an event listener in this manner
be sure it is added only once, it is permanent (can not be removed)
untill the object it was added to is destroyed.
WindowEventHandlers.onbeforeunload | Event.returnValue | EventTarget.removeEventListener
Unloading documents