Stopping content script in chrome extension

孤街醉人 提交于 2019-12-04 19:03:49

window.close() is for closing a window, so no wonder it does not work.

"Unloading" a content-script is not possible, but if you want to remove an element (e.g. your div) from the DOM, just do:

elem.parentNode.removeChild(elem);

(Whether you bind this behaviour to a link/button in your <div> or have the browser-action, trigger an event in the background-page that sends a message to the corresponding content-script which in turn removes the element is up to you. (But clearly the former is much more straight-forward and efficient.)


If you, also, want your script to stop performing some other operation (e.g. handling click events) you could (among other things) set a flag variable to false (when removing the <div>) and then check that flag before proceeding with the operation (e.g. handling the event):

var enabled = true;
document.addEventListener('click', function (evt) {
    if (!enabled) {
        /* Do nothing */
        return;
    }

    /* I am 'enabled' - I'll handle this one */
    evt.preventDefault();
    ...

/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
enabled = false;

Notes:

  • If you plan on re-enabling the content-script upon browser-action button click, it is advisable to implement a little mechanism, where the background-page sends a message to the content-script asking it to re-enable itself. If the content-script is indeed injected but disabled, it should respond back (to confirm it got the message) and re-enable itself. If there is no response (meaning this is the first time the user clicks the button on this page, the background-page injects the content script.

  • If it is likely for the content script to be enabled-disabled multiple times in a web-pages life-cycle, it would be more efficient to "hide" the <div> instead of removing it (e.g.: div.style.display = 'none';).

  • If you only need to disable event handler, instead of using the enabled flag, it is probably more efficient to keep a reference to the listener you want to disable and call removeEventListener().

E.g.:

function clickListener(evt) {
    evt.preventDefault();
    ...
}
document.addEventListener('click', clickListener);

/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
document.removeEventListener('click', clickListener);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!