我有一个网络扩展,它根据现有 token 将内容加载到弹出窗口中,我需要它向动态添加的按钮添加点击监听器,但我似乎无法让它在按钮之后添加被插入到页面中。不断出现 TypeError: document.getElementById(...) is null
。
我尝试使用 windows.onload
和 DOMContentLoaded
但没有成功
代码
// Get and display profile
function outputProfile(ACC_TOK) {
var request = new XMLHttpRequest();
request.open('GET', 'https://private-anon-535ecb43fa-trakt.apiary-mock.com/users/settings');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Bearer ' + ACC_TOK);
request.setRequestHeader('trakt-api-version', '2');
request.setRequestHeader('trakt-api-key', APP_KEY);
request.onreadystatechange = function () {
if (this.readyState === 4) {
// Get Response and put in array
var response = JSON.parse(this.responseText);
document.body.innerHTML = '<section id="traktProfile"><div id="traktAvatar"><img src="' + response.user.images.avatar.full + '" width="100px" height="100px" alt="' + response.user.name + '" /></div><div id="traktUser"><h1><a href="https://trakt.tv/users/' + response.user.ids.slug + '" target="_newtab">' + response.user.name + '</a></h1><p><i class="fa fa-map-marker"></i> ' + response.user.location + '</p></div></section><section id="traktSignOut"><a id="traktSignOutLink" class="profileLink">Sign Out</a></section>';
}
};
request.send();
}
// Check if Access Token Exists
chrome.storage.local.get("access_token", function (result) {
if (result.access_token && typeof result.access_token !== undefined) {
// Output Profile Page
outputProfile(result.access_token);
// Sign out button
window.onload = function() {
console.log("DOM Loaded");
document.getElementById("traktSignOutLink").addEventListener("click", traktSignOut);
};
} else {
// Output Authenctication Page
outputAuth();
}
});
最佳答案
如果我有错误的想法,请原谅我
为什么不添加点击这里
document.body.innerHTML = '<section id="traktProfile"><div id="traktAvatar"><img src="' + response.user.images.avatar.full + '" width="100px" height="100px" alt="' + response.user.name + '" /></div><div id="traktUser"><h1><a href="https://trakt.tv/users/' + response.user.ids.slug + '" target="_newtab">' + response.user.name + '</a></h1><p><i class="fa fa-map-marker"></i> ' + response.user.location + '</p></div></section><section id="traktSignOut"><a id="traktSignOutLink" class="profileLink" onclick="traktSignOut();">Sign Out</a></section>';
关于javascript - 在 WebExtension 中将 window.onload 与动态内容结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929140/