我正在使用一个小小的Chrome扩展程序为twitter.com上的以下页面上的每个“关注”用户添加一个按钮。
到目前为止,我已经让内容脚本足够工作,可以在页面加载时为每个“跟随”用户添加按钮,并在页面由twitter附加ajax时添加更多用户。 com向下滚动。我已经为每个按钮添加了一个onclick事件,包含在一个闭包中,这样当你点击它时,它会控制你。点击你点击的用户按钮。一切正常。
但是,当您在“关注者”页面(例如)之间单击并返回“关注”页面时,即使按钮仍在DOM中,onclick事件也不会再触发。好像onclick事件已经丢失了。 onclick事件可能会发生什么?
请注意,在返回“关注”页面并注意到现有按钮上丢失的事件后,向下滚动以向列表中添加更多用户会正确添加更多按钮及其onclick事件。当您点击“关注”页面时,我可以删除并重新添加按钮,但很高兴知道事件不存在的原因。
的manifest.json:
{
"name": "Twitter Button",
"version": "0.1",
"permissions": ["tabs"],
"content_scripts": [{
"matches": ["https://twitter.com/*"],
"css": ["style.css"],
"js": ["content_script.js"],
"run_at": "document_end"
}],
"manifest_version": 2
}
content_script.js:
function addButtons(){
// Only act on the 'following' page
// Note that I did try just setting the 'matches' attribute in the manifest file
// to just the 'following' page, but that didn't seem to fire consistently
// hence matching on any twitter page, and only acting on the 'following' page
if (document.URL.indexOf("twitter.com/following") > -1){
// Get a list of btn-group elements
var btnGroups = document.querySelectorAll(".btn-group");
for(var i = 0; i < btnGroups.length; i++){
var btnGroup = btnGroups[i];
var grandParent = btnGroup.parentNode.parentNode.nodeName;
// Only add note elements to list items that have not aleady had a note element added
if(btnGroup.children.length === 2 && grandParent === 'LI'){
var followedUser = btnGroup.getAttribute("data-screen-name");
// Create a closure for each btnGroup so that the correct handle is available to the current clicked button
var closure = (function(followedUser){
return function(){
var button = document.createElement("button");
button.innerHTML = "Click me";
button.className = "btn primary-btn";
button.onclick = function(){
console.log("Clicked " + followedUser + " button");
return false;
};
btnGroup.appendChild(button);
}
})(followedUser);
closure();
}
}
}
}
// Fire immediately (manifest is set to fire on document_end)
addButtons();
// Register a MutationObserver for further DOM changes
var observer = new MutationObserver(function(mutations, observer){
addButtons();
});
observer.observe(document, {
subtree: true,
attributes: true
});
由于