Chrome extension: callback function not getting called - javascript

I am developing a small extension( https://docs.google.com/leaf?id=0B5ZSnXcRXnSpMmM0NTFiNGEtMzEzZS00M2YzLWI4MzItMmVmNmM3OGE1MDRh&hl=en&authkey=CLzGpOMN ) that saves all tabs in a particular window, while closing that session.
In this, when I am trying to restore the session, I am not getting callback function getting called, though the new window is successfully opened.
The funny thing is, when in developer mode, using developer tools, the callback function gets called and restored all tabs.
Please help me.
Here is the code:
function restoreTabs( saveTabName )
{
var tabVals = window.localStorage.getItem(saveTabName);
if (tabVals == null)
return;
var callbackFunc = function (window, tabValList) {
//alert('created window');
for (var i = 0; i < tabValList.length; i++) {
var tab = eval('(' + tabValList[i] + ')');
var newTabObj = {
windowId: window.id,
index: tab.index,
url: tab.url,
selected: tab.selected,
pinned: tab.pinned
};
chrome.tabs.create(newTabObj);
}
};
var tabValList = tabVals.split('|');
chrome.windows.create(null, function (win) { callbackFunc(win, tabValList); });
}

Interesting problem. Popup is getting automatically closed when you create a new window (and as a result popup code execution is terminated), that's why it works in developer mode only because it forces the popup to stay open. You need to move restoreTabs() function to a background page, you can still easily call it from your popup:
linka.onclick = function () {
chrome.extension.getBackgroundPage().restoreTabs('saveTabs'+savetabName);
};

Related

JavaScript callback / async problem? Background script of Chrome Extension stops function before finishing

I am trying to create a small crawler as a chrome extension. How it works is:
Open new window or tab.
Perform a search for Google / Google News / YouTube with given keywords.
Store information of the results in a small database
I first created and tested the functions with a popup.html. There it works perfectly.You click on a button and all pages are visited and the results are stored in a database. But I want to start the program without clicking anything first. That's why I migrated it to background.js. There it also works, but only if the Service Worker / DevTool console is open. Only then it runs completely.
I would be grateful for any helpful answer.
const keywords = [
"Keyword1",
"Keyword2",
// ...
"Keyword13"
];
chrome.runtime.onStartup.addListener(() => {
chrome.tabs.onUpdated.addListener(loadingWindow);
openWindow();
});
// Opens new Window or Tab with the correct URL
function openWindow() {
chrome.tabs.onUpdated.addListener(loadingWindow);
if (runs == 0) {
chrome.windows.create({ url: getUrl(keywords[runs]), type: "normal" }, newWindow => {
window_id = newWindow.id;
});
} else {
chrome.tabs.update(tab_id, { url: getUrl(keywords[runs]) });
}
}
// Wait to load the new tab
function loadingWindow(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.status == 'complete' && tab.windowId == window_id) {
tab_id = tabId;
console.log(tab.windowId);
chrome.tabs.onUpdated.removeListener(loadingWindow);
chrome.tabs.sendMessage(tab.id, { text: source }, doStuffWithDom);
}
};
// Get information from content script -> payload and then send to database
function doStuffWithDom(domContent) {
let payload = {... }
var data = new FormData();
data.append("json", JSON.stringify(payload));
fetch(".../store.php", { method: "POST", body: data });
crawlDone();
}
// open new window / tab or close the open window
function crawlDone() {
runs++;
if (runs < keywords.length) {
openWindow();
} else if (runs == keywords.length) {
chrome.windows.remove(window_id);
}
};
I switched to Manifest version 2. Then I could include the Background.js via the Background.html, which also runs to the end.

Access data(set) from popup window with JQuery

I have a page that will open a popup and after something is done on that popup and user close it I want to get data from table / tds. Here is my calling function:
function clicked() {
windowOpener("SiteMap.html");
popupWin.onbeforeunload = function () {
var a = $("#drawTable", popupWin.document);
var tds = $(a).find("td");
tds.each(function () {
var p = $(this).data('point');
if (JSON.stringify(p.values) !== JSON.stringify(point.values)) { //here comes error, to this line
console.log(p.values);
}
})
};
}
.data('point') is created and populated already on that popup page, but still I am getting that $(this).data('point') is undefined. So, is it possible that in that point data is already destroyed? What is your recommendation how to deal with this?
thanks

open window and run function on that window

I'd like to open a new window, this window has a list of objects, and these objects should be filtered based on a selection from the previous window. I figured I can filter the list through a function, but how do I run said function?
This is what I am able to do:
var popup = window.open('pageURL');
$(popup.document).ready(function() {
// this is where function should be
popup.alert('HelloWorld');
});
But how do I change the alert to a function?
If I have a function on my other app , function test() { alert('HelloWorld'};
How do I run this function from my first app?
Swapping popup.alert('HelloWorld'); with popup.test(); did not work.
You need the reference to the window opened to call functions in the new window, like:
var oNewWindow = window.open("new.window.url", "mywindow");
oNewWindow.onload = function(){oNewWindow.window.newWindowFunction();};
I ended up with this solution
var popup = window.open('http://s234-0057/actiontracker/SiteAssets/Avvik/html/app.aspx');
var readyStateCheckInterval = setInterval(function() {
if (popup.document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
popup.test();
}
}, 50);
Where I check if the popup window is ready, and when it is, cancel check and run function. Solution is from top answer on this question, by #this.lau_
You can write it like this:
function myFunction(){
alert('HelloWorld');
}
var popup = window.open('pageURL');
$(popup.document).ready(function() {
popup.eval(myFunction + "");
popup.myFunction();
});
myFunction in file that contains this code will run in page with pageURL address.

Firefox extension, storing variable value until firefox is restarted

Building a Firefox extension and I require to save a value after an action has been performed by the user. I need this value to persist until Firefox is restarted. I`m testing with this code.
Components.utils.import("chrome://***/content/symbols.jsm");
window.addEventListener("load", function() { myExtension.init() }, false);
var myExtension = {
init: function() {
document.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function() {
if (blocked == 0) {
alert("OFF");
}
else {
alert("ON");
}
blocked = 1;
}
}
symbols.jsm
var EXPORTED_SYMBOLS = ["blocked"];
var blocked = 0;
With this code Firefox is started and "OFF" is shown because variable has not been set yet.( as intended) Navigating to a different page and even opening a new tab will show "ON" how ever as soon as a new window is opened the variable is lost and "OFF" is shown. How can I make the variable value persist until all Firefox windows are closed(restart).
I do not want to set this in a preference in about:config as this can be easily changed by the user.
You can use JavaScript code modules https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using
Your module should export functions instead of just variables e.g.
var EXPORTED_SYMBOLS = ["getBlocked", "setBlocked"];
var blocked = 0;
function getBlocked() {
return blocked;
}
function setBlocked(value) {
blocked = value;
}
and then use the functions instead of the variable name

FireFox Toolbar Prefwindow unload/acceptdialog Event to Update the toolbar

I'm trying to develop a firefox toolbar ;)
so my structure is
In the options.xul is an PrefWindow which i'm opening over an
<toolbarbutton oncommand="esbTb_OpenPreferences()"/>
function esbTb_OpenPreferences() {
window.openDialog("chrome://Toolbar/content/options.xul", "einstellungen", "chrome,titlebar,toolbar,centerscreen,modal", this);}
so in my preferences i can set some checkboxes which indicates what links are presented in my toolbar. So when the preferences window is Closed or the "Ok" button is hitted I want to raise an event or an function which updates via DOM my toolbar.
So this is the function which is called when the toolbar is loaded. It sets the links visibility of the toolbar.
function esbTB_LoadMenue() {
var MenuItemNews = document.getElementById("esbTb_rss_reader");
var MenuItemEservice = document.getElementById("esbTb_estv");
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowNews"))) {
MenuItemNews.style.display = 'none';
}
if (!(prefManager.getBoolPref("extensions.esbtoolbar.ShowEservice"))) {
MenuItemEservice.style.display = 'none';
}
}
So I tried some thinks like adding an eventlistener to the dialog which doesn't work... in the way I tried...
And i also tried to hand over the window object from the root window( the toolbar) as an argument of the opendialog function changed the function to this.
function esbTB_LoadMenue(RootWindow) {
var MenuItemNews = RootWindow.getElementById("esbTb_rss_reader");
var MenuItemEservice = RootWindow.getElementById("esbTb_estv");}
And then tried to Access the elements over the handover object, but this also not changed my toolbar at runtime.
So what i'm trying to do is to change the visibile links in my toolbar during the runtime and I don't get it how I should do that...
thanks in advance
-------edit-------
var prefManager = {
prefs: null,
start: function()
{
this.prefs = Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
this.prefs.addObserver("", this, false);
},
end: function()
{
this.prefs.removeObserver("", this);
},
observe: function(subject, topic, data)
{
if (topic != "nsPref:changed")
{
return;
}
//Stuff what is done when Prefs have changed
esbTB_LoadMenue();
},
SetBoolPref: function(pref,value)
{
this.prefs.setBoolPref(pref,value);
},
GetBoolPref: function(pref)
{
this.prefs.getBoolPref(pref);
}
}
So this is my implementation.
The trick is to listen to preference changes. That way your toolbar updates whenever the prefs change -- regardless if it happened through your PrefWindow, about:config or some other mechanism.
In Toolbar.js you do the following
var esbTB_observe = function(subject, topic, data) {
if (topic != "nsPref:changed") {
return;
}
// find out which pref changed and do stuff
}
var esbTB_init = function() {
prefs =
Components.classes["#mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.esbtoolbar.");
prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
prefs.addObserver("", esbTB_observe, false);
}
// Init addin after window loaded
window.addEventListener("load", esbTB_init, false);
Now, when the window loads, the esbTB_init() function is called in which the observer to the pref branch "extensions.esbtoolbar." is added. Later, when a pref in the branch is changed, the esbTB_observe() function is automatically called.
In esbTB_observe() you have to read the values of your prefs and adjust the toolbar.

Categories

Resources