sohel
sohel

Reputation: 375

cant' add listener in chrome extension

I'am trying to create chromium extension, but can't attach listeners to buttons in correct way. It must be noticed that I'am not very familiar with js, so mb the problem is in some missunderstanding conception or some element loading timing.

"background" : {"page" : "kbm.html"}

I'am using manifest v2, so inline js is disalowed, so i'am trying to add listeners in callback

here is kbm.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="kbm.js"></script>
    </head>
    <body>
        <button id="loadall">Open all saved</button>
    </body>
</html>

and here is kbm.js:

chrome.browserAction.onClicked.addListener(
        function(tab) {
            chrome.tabs.create( {'url': chrome.extension.getURL('kbm.html')}, 
                function(tab) {
                    alert(document.getElementById("loadall"));
                       document.getElementById("loadall").addEventListener("click",loadAll,false);
                });
        }
);

function loadAll(){
    alert("hallo");
}

After loading kbm.html and clicking the toolbar icon I can see alert message from chrome.tabs.create callback. But click on loadall button gives nothing.

I can see in debugger(with f12) that there is no listener on the button after page loading.

The syntax is seems to be ok, because I can dynamically add listener to button from js-console

>document.getElementById("loadall").addEventListener("click",loadAll);
undefined

and it appears in element description so I see alert from loadAll() call after click.

First I thougth that mb callback is called previous to all pages elements initialization and thus it can't find element with id="loadall", but acording to first alert with message

object HTMLButtonElement 

that is not the reason.

But I still don't understand why there is no callback attached to button at page load:(

I'v looked at examples but I cant blindly copy ther realisation I want to find what am I missing.

Thanks in advance.

Upvotes: 0

Views: 1752

Answers (1)

sohel
sohel

Reputation: 375

Eh...I just gave up and moved add button listeners logic to another place like that:

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('loadall').addEventListener('click', loadAll)
}

Upvotes: 1

Related Questions