Reputation: 6615
So lets say I am making an addon/extension for firefox/chrome. I have a popup with one button. It looks like this:
When the button is clicked I want some function to execute, and I want it to continue to execute even after the popup loses focus and disappears.
The normal behavior is to close the popup as soon as it loses focus. So if I click the button then immediately click something else, the popup disappears and I get this message in the console:
Cannot send function call result: other side closed connection (calldata:
({path:"bookmarks.getTree", args:[]}))
No error checking or using onbeforeunload works.
Here's a minimal example:
Manifest.json
{
"manifest_version": 2,
"name": "delete bookmarks",
"version": "0.1",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": ["management", "bookmarks", "http://*/"],
"background": {
"scripts": ["doStuff.js"]
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["doStuff.js"]
}]
}
popup.html
<!DOCTYPE html>
<html>
<button id="doStuff">doStuff</button>
<script src="doStuff.js"></script>
</html>
doStuff.js
var button = document.getElementById("doStuff");
button.addEventListener("click", function() {
doStuff();
}, false);
function doStuff(){
chrome.bookmarks.getTree(deleteAllBookmarks);
}
function deleteAllBookmarks(result){ //JUST AN EXAMPLE!
//delete/remove ALL bookmarks
for(var i = 0 ; i < result[0].children.length; i ++){ //get children of root
var child = result[0].children[i];
for(var j = 0 ; j < child.children.length; j++){ //get children of children of root
var childchild = child.children[j];
console.log("deleting id " + childchild.id);
chrome.bookmarks.removeTree(childchild.id, success); //delete everything
}
}
}
function success(result){
alert("Success");
}
So, again, I am trying to finish executing javascript code even after the parent html page is closed. It seems like this should be easy, since I am loading the script both as a content_script and a background script, but I cannot figure it out and there are no matching SO posts. Any help is appreciated.
Upvotes: 0
Views: 1397
Reputation: 4103
You should messaging of chrome.
When press button, popup
will send message to background
, and background
will listen and do something.
You can't do it if just use popup page
.
And if you want to do something with active page
, you need create listener in that page (add script with content_scripts
).
Upvotes: 1