Facebook OG Meta with Angular and Node - javascript

I am trying to get my angular / node application to render dynamic Open graph meta content.
I have been trying to follow this tutorial http://www.codewarmer.com/posts/1394433236-configuring-angularjs-nodejs-for-search-bots#!
I am having some problems with phantom working with node, my issue seems to be similar to this Error message when using PhantomJS, breaks at random intervals
except that my error does not happen at random intervals, it happens all the time.
EDIT: Here is my code
In my server.js I require a module i created based on the above tut called PhantomHandler.js and it is called like so.
var crawler = require('./modules/PhantomHandler');
This is what PhantomHandler.js looks like:
var phantom = require('phantom');
var models = require('../models');
mongoose = require('mongoose');
Snapshot = models.Snapshot;
url = require('url');
var baseUrl = 'my url';
function crawlSite(idx, arr, page, callback) {
crawlUrl(arr[idx], page, function(data) {
data.links.forEach(function(link) {
if (arr.indexOf(link) < 0)
arr.push(link);
});
Snapshot.upsert(data);
if (++idx === arr.length)
callback();
else
crawlSite(idx, arr, page, callback);
});
}
function startPhantom(cb) {
phantom.create(function(ph) {
phInstance = ph;
ph.createPage(function(page) {
phPage = page;
cb(ph, page);
});
});
}
function crawlUrl(path, page, cb) {
uri = url.resolve(baseUrl, path);
page.open(uri, function(status) {
var evaluateCb = function(result) {
result.path = path;
cb(result);
};
//Timeout 2000ms seems pretty enough for majority ajax apps
setTimeout(function() {
if (status == 'success')
page.evaluate(function() {
var linkTags = document.querySelectorAll('a:not([rel="nofollow"])');
var links = [];
for (var i = 0, ln; ln = linkTags[i]; i++)
links.push(ln.getAttribute('href'));
return {
'links': links,
'html': document.documentElement.outerHTML
};
}, evaluateCb);
}, 2000);
});
}
exports.crawlAll = function(callback) {
startPhantom(function(ph, page) {
crawlSite(0, ['/'], page, function() {
ph.exit();
callback();
});
});
};
exports.crawlOne = function(path, callback) {
startPhantom(function(ph, page) {
crawlUrl(path, page, function(data) {
Snapshot.upsert(data);
ph.exit();
callback();
});
});
};
When i run this code my exact error is:
phantom stderr: 'phantomjs' is not recognized as an internal or exte
,
operable program or batch file.
assert.js:92
throw new assert.AssertionError({
^
AssertionError: abnormal phantomjs exit code: 1
at Console.assert (console.js:102:23)
at ChildProcess.<anonymous> (path to node modules\node_modules\phantom\phantom.js:150:28)
at ChildProcess.emit (events.js:98:17)
at Process.ChildProcess._handle.onexit (child_process.js:809:12)
My question: Is this the best easiest way to go about getting angular to play nicely with Facebook OG? If it is can anyone else confirm if they have managed to get this technique to work with out phantom throwing an assertion error as described above.
It seems like this should be a relatively common job and I am surprised that I haven't found a nice straight forward tutorial on how to get this to work, unless i just haven't looked properly :s
Thanks

Okay,
Because my question was essentially "What is the best way to get angular and node to respond to Facebook with the correct page meta". I am now in a position to post my answer to this.
As stated above I think that using the phantom.js method described above requires phantom to be installed and to run as a separate process on the node.js server. (Can anyone confirm or deny this?)
For my situation I just wanted a user to be able to post a link from the site onto Facebook and for Facebook to return a nice looking link using open graph meta.
With that in mind I decided to skip the phantom.js step from the solution in the tutorial above. Instead I rolled some code which essentially saves an HTML snippet into the DB when a user hits a page. The HTML snippet just contains the meta tags I need for Facebook. I then use the last part of the above tutorial to direct Facebook bots to my saved HTML snippet.
It seems to work pretty well.

Related

Re-using same instance again webdriverJS

I am really new to Selenium. I managed to open a website using the below nodejs code
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
console.log(driver);
driver.get('https://web.whatsapp.com');
//perform all other operations here.
https://web.whatsapp.com is opened and I manually scan a QR code and log in. Now I have different javascript files to perform actions like delete, clear chat inside web.whatsapp.com etc...
Now If I get some error, I debug and when I run the script again using node test.js, it takes another 2 minutes to load page and do the steps I needed. I just wanted to reopen the already opened tab and continue my script instead new window opens.
Edit day 2 : Still searching for solution. I tried below code to save object and reuse it.. Is this the correct approach ? I get a JSON parse error though.
var o = new chrome.Options();
o.addArguments("user-data-dir=/Users/vishnu/Library/Application Support/Google/Chrome/Profile 2");
o.addArguments("disable-infobars");
o.addArguments("--no-first-run");
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).setChromeOptions(o).build();
var savefile = fs.writeFile('data.json', JSON.stringify(util.inspect(driver)) , 'utf-8');
var parsedJSON = require('./data.json');
console.log(parsedJSON);
It took me some time and a couple of different approaches, but I managed to work up something I think solves your problem and allows to develop tests in a rather nice way.
Because it does not directly answer the question of how to re-use a browser session in Selenium (using their JavaScript API), I will first present my proposed solution and then briefly discuss the other approaches I tried. It may give someone else an idea and help them to solve this problem in a nicer/better way. Who knows. At least my attempts will be documented.
Proposed solution (tested and works)
Because I did not manage to actually reuse a browser session (see below), I figured I could try something else. The approach will be the following.
Idea
Have a main loop in one file (say init.js) and tests in a separate file (test.js).
The main loop opens a browser instance and keeps it open. It also exposes some sort of CLI that allows one to run tests (from test.js), inspect errors as they occur and to close the browser instance and stop the main loop.
The test in test.js exports a test function that is being executed by the main loop. It is passed a driver instance to work with. Any errors that occur here are being caught by the main loop.
Because the browser instance is opened only once, we have to do the manual process of authenticating with WhatsApp (scanning a QR code) only once. After that, running a test will reload web.whatsapp.com, but it will have remembered that we authenticated and thus immediately be able to run whatever tests we define in test.js.
In order to keep the main loop alive, it is vital that we catch each and every error that might occur in our tests. I unfortunately had to resort to uncaughtException for that.
Implementation
This is the implementation of the above idea I came up with. It is possible to make this much fancier if you would want to do so. I went for simplicity here (hope I managed).
init.js
This is the main loop from the above idea.
var webdriver = require('selenium-webdriver'),
by = webdriver.By,
until = webdriver.until,
driver = null,
prompt = '> ',
testPath = 'test.js',
lastError = null;
function initDriver() {
return new Promise((resolve, reject) => {
// already opened a browser? done
if (driver !== null) {
resolve();
return;
}
// open a new browser, let user scan QR code
driver = new webdriver.Builder().forBrowser('chrome').build();
driver.get('https://web.whatsapp.com');
process.stdout.write("Please scan the QR code within 30 seconds...\n");
driver.wait(until.elementLocated(by.className('chat')), 30000)
.then(() => resolve())
.catch((timeout) => {
process.stdout.write("\b\bTimed out waiting for code to" +
" be scanned.\n");
driver.quit();
reject();
});
});
}
function recordError(err) {
process.stderr.write(err.name + ': ' + err.message + "\n");
lastError = err;
// let user know that test failed
process.stdout.write("Test failed!\n");
// indicate we are ready to read the next command
process.stdout.write(prompt);
}
process.stdout.write(prompt);
process.stdin.setEncoding('utf8');
process.stdin.on('readable', () => {
var chunk = process.stdin.read();
if (chunk === null) {
// happens on initialization, ignore
return;
}
// do various different things for different commands
var line = chunk.trim(),
cmds = line.split(/\s+/);
switch (cmds[0]) {
case 'error':
// print last error, when applicable
if (lastError !== null) {
console.log(lastError);
}
// indicate we are ready to read the next command
process.stdout.write(prompt);
break;
case 'run':
// open a browser if we didn't yet, execute tests
initDriver().then(() => {
// carefully load test code, report SyntaxError when applicable
var file = (cmds.length === 1 ? testPath : cmds[1] + '.js');
try {
var test = require('./' + file);
} catch (err) {
recordError(err);
return;
} finally {
// force node to read the test code again when we
// require it in the future
delete require.cache[__dirname + '/' + file];
}
// carefully execute tests, report errors when applicable
test.execute(driver, by, until)
.then(() => {
// indicate we are ready to read the next command
process.stdout.write(prompt);
})
.catch(recordError);
}).catch(() => process.stdin.destroy());
break;
case 'quit':
// close browser if it was opened and stop this process
if (driver !== null) {
driver.quit();
}
process.stdin.destroy();
return;
}
});
// some errors somehow still escape all catches we have...
process.on('uncaughtException', recordError);
test.js
This is the test from the above idea. I wrote some things just to test the main loop and some WebDriver functionality. Pretty much anything is possible here. I have used promises to make test execution work nicely with the main loop.
var driver, by, until,
timeout = 5000;
function waitAndClickElement(selector, index = 0) {
driver.wait(until.elementLocated(by.css(selector)), timeout)
.then(() => {
driver.findElements(by.css(selector)).then((els) => {
var element = els[index];
driver.wait(until.elementIsVisible(element), timeout);
element.click();
});
});
}
exports.execute = function(d, b, u) {
// make globally accessible for ease of use
driver = d;
by = b;
until = u;
// actual test as a promise
return new Promise((resolve, reject) => {
// open site
driver.get('https://web.whatsapp.com');
// make sure it loads fine
driver.wait(until.elementLocated(by.className('chat')), timeout);
driver.wait(until.elementIsVisible(
driver.findElement(by.className('chat'))), timeout);
// open menu
waitAndClickElement('.icon.icon-menu');
// click profile link
waitAndClickElement('.menu-shortcut', 1);
// give profile time to animate
// this prevents an error from occurring when we try to click the close
// button while it is still being animated (workaround/hack!)
driver.sleep(500);
// close profile
waitAndClickElement('.btn-close-drawer');
driver.sleep(500); // same for hiding profile
// click some chat
waitAndClickElement('.chat', 3);
// let main script know we are done successfully
// we do so after all other webdriver promise have resolved by creating
// another webdriver promise and hooking into its resolve
driver.wait(until.elementLocated(by.className('chat')), timeout)
.then(() => resolve());
});
};
Example output
Here is some example output. The first invocation of run test will open up an instance of Chrome. Other invocations will use that same instance. When an error occurs, it can be inspected as shown. Executing quit will close the browser instance and quit the main loop.
$ node init.js
> run test
> run test
WebDriverError: unknown error: Element <div class="chat">...</div> is not clickable at point (163, 432). Other element would receive the click: <div dir="auto" contenteditable="false" class="input input-text">...</div>
(Session info: chrome=57.0.2987.133)
(Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 4.9.0-2-amd64 x86_64)
Test failed!
> error
<prints complete stacktrace>
> run test
> quit
You can run tests in other files by simply calling them. Say you have a file test-foo.js, then execute run test-foo in the above prompt to run it. All tests will share the same Chrome instance.
Failed attempt #1: saving and restoring storage
When inspecting the page using my development tools, I noticed that it appears to use the localStorage. It is possible to export this as JSON and write it to a file. On a next invocation, this file can be read, parsed and written to the new browser instance storage before reloading the page.
Unfortunately, WhatsApp still required me to scan the QR code. I have tried to figure out what I missed (cookies, sessionStorage, ...), but did not manage. It is possible that WhatsApp registers the browser as being disconnected after some time has passed. Or that it uses other browser properties (session ID?) to recognize the browser. This is pure speculating from my side though.
Failed attempt #2: switching session/window
Every browser instance started via WebDriver has a session ID. This ID can be retrieved, so I figured it may be possible to start a session and then connect to it from the test cases, which would then be run from a separate file (you can see this is the predecessor of the final solution). Unfortunately, I have not been able to figure out a way to set the session ID. This may actually be a security concern, I am not sure. People more expert in the usage of WebDriver might be able to clarify here.
I did find out that it is possible to retrieve a list of window handles and switch between them. Unfortunately, windows are only shared within a single session and not across sessions.

Run Node.js file on button click event

In my current project, we have a HTML page. In HTML page, we have several buttons, for instance we have buttons for Temperature Sensor, Humidity Sensor, Alarm etc. When we click on a button than in back-end it will run corresponding Node.js file, for instance when we click on Temperature sensor button than it will run TemperatureSensor.js file located in the same path. The code for HTML page is as shown below:
The code of TemperatureSensor.js is as below:
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://test.mosquitto.org:1883');
var NUM_SAMPLE_FOR_AVG = 5;
var numSample = 0;
var tempCelcius = 0;
var currentAvg = 0;
client.subscribe('tempMeasurement');
client.on('message', function(topic, payload) {
if (topic.toString() == "tempMeasurement") {
sensorMeasurement = JSON.parse(payload);
console.log("tempValue is " + sensorMeasurement.tempValue);
if (numSample <= NUM_SAMPLE_FOR_AVG) {
numSample = numSample + 1;
if (sensorMeasurement.unitOfMeasurement == 'F') {
tempCelcius = ((sensorMeasurement.tempValue - 32) * (5 / 9));
} else {
tempCelcius = sensorMeasurement.tempValue;
}
currentAvg = parseFloat(currentAvg) + parseFloat(tempCelcius);
if (numSample == NUM_SAMPLE_FOR_AVG) {
currentAvg = currentAvg / NUM_SAMPLE_FOR_AVG;
var avgTemp = {
"tempValue" : parseFloat(currentAvg),
"unitOfMeasurement" : sensorMeasurement.unitOfMeasurement
};
client.publish('roomAvgTempMeasurement', JSON
.stringify(avgTemp));
console.log("Publishing Data roomAvgTempMeasurement ");
numSample = 0;
currentAvg = 0;
}
}
}
});
The problem is when we clicked on TemperatureSensor button in browser than it display error: TemperatureSensor.js:1 Uncaught ReferenceError: require is not defined. if the content of TemeperatureSensor is console.log("Hello") than it displays Hello in the console of browser. How to provide dependency ??Why we need to do this bcoz if we want to run TemperatureSensor, HumiditySensor etc. than we need to run these in terminal, for instance if we want to run TemperatureSensor than in terminal we have to write sudo node TempeatureSensor.js. This require more manual efforts so in order to reduce this effort we need such kind of HTML page. How to resolve the about problem ??
You can't run Node.js code in the browser, they're completely separate environments (for example, browsers do not have the require function, hence why you're getting that error). Your best bet is to look into creating a REST service of some kind (using Express, Hapi or Restify, most likely) that will allow you to call a Node.js server through HTTP.
This is a decent introduction to the topic - it uses MongoDB for data persistence, but this is in no way a requirement when it comes to making stuff like this. In your case, you'll basically just have to define a route for Temp and Humidity, run your code to get the data in the route handler, and then send JSON data back on the response object. You'll then be able to use jQuery (or any number of other libraries) to make AJAX requests to these routes.
EDIT: After looking at the MQTT GitHub page, there is another option - the library can be used in the browser if bundled using a tool like Browserify or Webpack. Given the complexities of learning to write and maintain REST services, this may well be a better option.

Intercept new downloads in Firefox Addon SDK

I have written a simple download manager for Windows and I would like to create an addon for Firefox that when enabled intercepts new downloads in Firefox and sends them to the download manager.
I have already done this for Google Chrome using:
chrome.downloads.onCreated.addListener(function(details) {
// stop the download
chrome.downloads.cancel(details.id, null);
}
The question is how can I achieve something similar using the Firefox add-on SDK.
I see there is a way of intercepting page loads to view the content / headers which might be helpful but then I won't know if the request will turn into a download or not.
Firefox add-on SDK: Get http response headers
I could perhaps look for a content type that is not text/html or check for a content disposition header but that could cause problems if I don't correctly handle all cases.
Is there no way of accessing the download manager using the JS SDK or some way of knowing when a download has been started / being started and stop it?
The http-on-examine-response observer that the linked question discusses is the wrong way to go. It concerns all requests not just downloads.
Instead use the Downloads.jsm to observe new downloads, then cancel them, and so on.
To load Downloads.jsm in the SDK use:
const {Cu} = require("chrome");
Cu.import("resource://gre/modules/Downloads.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Then you can add your listener.
let view = {
onDownloadAdded: function(download) {
console.log("Added", download);
},
onDownloadChanged: function(download) {
console.log("Changed", download);
},
onDownloadRemoved: function(download) {
console.log("Removed", download);
}
};
Task.spawn(function() {
try {
let list = yield Downloads.getList(Downloads.ALL);
yield list.addView(view);
} catch (ex) {
console.error(ex);
}
});
The linked MDN docs have more information and samples.
Since your add-on is a restartless SDK add-on, you'll need to remove the listener again using .removeView on unload, or else there will be a memory leak.
Here's the JSM way.
Components.utils.import("resource://gre/modules/Downloads.jsm");
Components.utils.import("resource://gre/modules/Task.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var view = {
onDownloadChanged: function (download) {
console.log(download, 'Changed');
if (download.succeeded) {
var file = new FileUtils.File(this.target.path);
console.log('file', file);
}
}
};
var list;
Task.spawn(function () {
list = yield Downloads.getList(Downloads.ALL);
list.addView(view);
}).then(null, Components.utils.reportError);
Remember to removeView to stop listening. Can do this anywhere, like in shutdown function or whatever, doesn't have to be within that Task.spawn so list must be global var.
list.removeView(view); //to stop listening
Here's the old way, which seems to still work. Although I thought they said they're going to take out the old downloadManager:
var observerService = Components.classes["#mozilla.org/download-manager;1"].getService(Components.interfaces.nsIDownloadManager);
observerService.addListener({
onDownloadStateChange: function (state, dl) {
console.log('dl=', dl);
console.log('state=', state);
console.log('targetFile', dl.targetFile);
if (state == 7 && dl.targetFile.leafName.substr(-4) == ".txt") {
//guys just downloaded (succesfully) a .txt file
}
}
});
Heres a mozillazine with some more on this: http://forums.mozillazine.org/viewtopic.php?f=19&t=2792021

Downloading multiple images with Phonegap - FileTransfer

I have built an offline app in Phonegap, the JSON data gets pushed and gets to where it needs to go. But there are always a bunch of images that need to follow, and html5 cache will just not do it seeing it clears when an app is closed. I have been breaking my nugget on this for quite a while now.
The issue is that you want to check if the image exists on the file system. I've chosen to do so with a "async:false" AJAX call, and therefore have the code running up to a point. I haven't used the phonegap (almost hack) way by writing and setting overwrite to false (which produces an error) seeing that was another async function I didn't want to deal with (wherein lies the problem: async).
Another problem is that the Phonegap browser allows best for 3 downloads at the time (looked it up). My previous function was suffering from this debacle as it would just cut off downloading images if the amount simultaneous downloads was to high, which was around 20 to 40 (depending on size) images at the time (which of course is not strange seeing download speed plummets when you divide it over multiple downloads at the time).
So the question is, how to build:
A function that loops through JSON data (image variables).
Downloads them three at the time (and set the meta data because Apple told it had to)
Deletes from disk those who are not needed anymore (this last one is problem all over the inet as far as I've read, so we'll keep this optional and because by now I really don't actually care about space anymore).
Should run a function when all images are downloaded.
My code as far:
var datadir = "";
var pics_at_the_time = 0;
var external_url_pics = "http://Folder on server where images are";
// new_config.pics holds the JSON data. Built: '[ key (same as id) { "id": 1234567890, "tld":"jpg" }'. id+'.'+tld = the image name.
window.requestFileSystem( // get the root folder path
LocalFileSystem.PERSISTENT,
0,
function(fileSystem) {
datadir = fileSystem.root.fullPath;
},
function() {
console.log("Could not get root FS");
}
);
function fetch_images() {
var len = new_config.pics.length; // amount of pictures that need to be here
var all_in_counter = 0;
$.each(new_config.pics,function(index,val){ // loop through all pics
pic_exists(val);
});
}
function pic_exists(val) {
$.ajax({ // pic on disk or not
async:false,
url: 'file://'+datadir+'/'+val.id+'.'+val.tld, //or your url
success: function(){
var obj = val.id;
delete new_config.pics.obj;
},
error: function(){
var obj = val.id;
delete new_config.pics.obj;
downloadImage(val);
}
});
}
function downloadImage(val){
if(pics_at_the_time < 3) { // only 3 at a time. else wait for a download to finish
pics_at_the_time++;
var ft = new FileTransfer();
ft.download(
external_url_pics+val.id+'.'+val.tld,
datadir + "/" + val.id+'.'+val.tld,
function(entry) {
if(debug_console) { console.log("download complete: " + entry.name); }
entry.setMetadata(function(metadata) { } , function(error) { console.log("Could not set meta data: "+val.id); }, { "com.apple.MobileBackup": 1}); // no apple cloudbackup for these pics. We can always re-download apparently
pics_at_the_time--;
fetch_images();
},
function(error) {
if(debug_console) { console.log("download error target " + error.target); }
pics_at_the_time--;
fetch_images();
});
}
}
As you can probably tell, the code is not very sophisticated and it definitely does not check for already existing images. Cause although this works, it is far from perfect seeing it reloops the bunch every time, which at first seemed like a good idea. But now I'm having second thoughts.
Any help is obviously appreciated

Error: The page has been destroyed and can no longer be used

I'm developing an add-on for the first time. It puts a little widget in the status bar that displays the number of unread Google Reader items. To accommodate this, the add-on process queries the Google Reader API every minute and passes the response to the widget. When I run cfx test I get this error:
Error: The page has been destroyed and can no longer be used.
I made sure to catch the widget's detach event and stop the refresh timer in response, but I'm still seeing the error. What am I doing wrong? Here's the relevant code:
// main.js - Main entry point
const tabs = require('tabs');
const widgets = require('widget');
const data = require('self').data;
const timers = require("timers");
const Request = require("request").Request;
function refreshUnreadCount() {
// Put in Google Reader API request
Request({
url: "https://www.google.com/reader/api/0/unread-count?output=json",
onComplete: function(response) {
// Ignore response if we encountered a 404 (e.g. user isn't logged in)
// or a different HTTP error.
// TODO: Can I make this work when third-party cookies are disabled?
if (response.status == 200) {
monitorWidget.postMessage(response.json);
} else {
monitorWidget.postMessage(null);
}
}
}).get();
}
var monitorWidget = widgets.Widget({
// Mandatory widget ID string
id: "greader-monitor",
// A required string description of the widget used for
// accessibility, title bars, and error reporting.
label: "GReader Monitor",
contentURL: data.url("widget.html"),
contentScriptFile: [data.url("jquery-1.7.2.min.js"), data.url("widget.js")],
onClick: function() {
// Open Google Reader when the widget is clicked.
tabs.open("https://www.google.com/reader/view/");
},
onAttach: function(worker) {
// If the widget's inner width changes, reflect that in the GUI
worker.port.on("widthReported", function(newWidth) {
worker.width = newWidth;
});
var refreshTimer = timers.setInterval(refreshUnreadCount, 60000);
// If the monitor widget is destroyed, make sure the timer gets cancelled.
worker.on("detach", function() {
timers.clearInterval(refreshTimer);
});
refreshUnreadCount();
}
});
// widget.js - Status bar widget script
// Every so often, we'll receive the updated item feed. It's our job
// to parse it.
self.on("message", function(json) {
if (json == null) {
$("span#counter").attr("class", "");
$("span#counter").text("N/A");
} else {
var newTotal = 0;
for (var item in json.unreadcounts) {
newTotal += json.unreadcounts[item].count;
}
// Since the cumulative reading list count is a separate part of the
// unread count info, we have to divide the total by 2.
newTotal /= 2;
$("span#counter").text(newTotal);
// Update style
if (newTotal > 0)
$("span#counter").attr("class", "newitems");
else
$("span#counter").attr("class", "");
}
// Reports the current width of the widget
self.port.emit("widthReported", $("div#widget").width());
});
Edit: I've uploaded the project in its entirety to this GitHub repository.
I think if you use the method monitorWidget.port.emit("widthReported", response.json); you can fire the event. It the second way to communicate with the content script and the add-on script.
Reference for the port communication
Reference for the communication with postMessage
I guess that this message comes up when you call monitorWidget.postMessage() in refreshUnreadCount(). The obvious cause for it would be: while you make sure to call refreshUnreadCount() only when the worker is still active, this function will do an asynchronous request which might take a while. So by the time this request completes the worker might be destroyed already.
One solution would be to pass the worker as a parameter to refreshUnreadCount(). It could then add its own detach listener (remove it when the request is done) and ignore the response if the worker was detached while the request was performed.
function refreshUnreadCount(worker) {
var detached = false;
function onDetach()
{
detached = true;
}
worker.on("detach", onDetach);
Request({
...
onComplete: function(response) {
worker.removeListener("detach", onDetach);
if (detached)
return; // Nothing to update with out data
...
}
}).get();
}
Then again, using try..catch to detect this situation and suppress the error would probably be simpler - but not exactly a clean solution.
I've just seen your message on irc, thanks for reporting your issues.
You are facing some internal bug in the SDK. I've opened a bug about that here.
You should definitely keep the first version of your code, where you send messages to the widget, i.e. widget.postMessage (instead of worker.postMessage). Then we will have to fix the bug I linked to in order to just make your code work!!
Then I suggest you to move the setInterval to the toplevel, otherwise you will fire multiple interval and request, one per window. This attach event is fired for each new firefox window.

Categories

Resources