How to use nsITimer in a Firefox Extension? - javascript

I am working on a Firefox extension, and wish to make use of a timer to control posting of data every 60 seconds.
The following is placed inside an initialization function in the main .js file:
var timer = Components.classes["#mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
timer.init(sendResults(true), 60000, 1);
However, when I try to run this I get the following error in the Firefox console:
"Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsITimer.init]" nsresult: "0x80004003"...
And so on. What did I do wrong?
UPDATE:
The following works for my needs, although the initial problem of using nsITimer instead still remains:
var interval = window.setInterval(function(thisObj) { thisObj.sendResults(true); }, 1000, this);
}
Useful links that explain why this works (documentation on setInterval/sendResults, as well as solution to the 'this' problem:
https://developer.mozilla.org/En/DOM/window.setTimeout
https://developer.mozilla.org/En/Window.setInterval (won't let me post more than two hyperlinks)
http://klevo.sk/javascript/javascripts-settimeout-and-how-to-use-it-with-your-methods/

nsITimer.init() takes an observer as first parameter. You probably want to use a callback instead:
timer.initWithCallback(function() {sendResults(true); }, 60000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
But window.setInterval() is easier to use nevertheless - if you have a window that won't go away (closing a window removes all intervals and timeouts associated with it).

Related

how to solve TypeError: cv.Mat is not a constructor opencv.js?

I have a problem using opencv.js when I want to detect aruco markers from my camera. Every time I try to use the method
let image = new cv.imread('img');
I get the following error:
TypeError: cv.Mat is not a constructor
at Object.matFromImageData (VM52998 opencv.js:55)
I tried to use this question to try and solve my issue. The solution from the question was to use async load, call onOpenCvReady() when the script is loaded, which will set a handler for onRuntimeInitialized event of cv. The handler should perform the necessary operations.
<script>
function onOpenCvReady() {
cv['onRuntimeInitialized']=()=>{
alert('OpenCV.js is ready.');
// do all operations
</script>
<script async src="<%= BASE_URL %>static/opencv.js" onload="onOpenCvReady();"></script>
However, when I tried to use the solution from the question I encoutered a problem:
the function onOpenCvReady() wasn't called at all.
In addition, I waited for more than 15 minutes (just to be sure) and then tried to use the line javascript let image = new cv.imread('img'); directly in console. Every move I made, and every step I took results in the same issue.
After going back to square 1, I had retried the most basic of solutions:
I just added this to my HTML page, instead of everything written here.
<script src="<%= BASE_URL %>static/opencv.js" id="opencvjs"></script>
This didn't directly worked, but after debugging some other areas of my code, I made sure that my page doesn't contain other errors (which are not related to this issue at all). For some reason I've yet to investigate and fully understand, having other errors while loading the opencv.js script has interrupted the loading process. Although it sounds unrelated, this had a huge effect on opencv commands.
The end result was magnificent:
let image = new cv.imread('img');
console.log(image);
OUTPUT:
Mat {$$: {…}}

HTML5 Drag&Drop - Event handling with jQuery

So I've stumbled upon this a several times and now I'm finally fed up with this topic. Searching and googleing about it confuses me every time and now I'll need to ask by myself here.
I'm up to implement native HTML5 drag&drop in a web app. It works fine in Chrome and in IE too (at least when I tried last time).
The problem now is, that event binding via jQuery wont work out properly in Firefox, whereas it does so in Chrome! This is my Code:
$(document).on('dragstart','.leistung', function(){
cedamed.handlers.dragElement(event);
});
And this is my handler:
this.dragElement = function(event){
var dataObj = {};
dataObj.category = event.target.getAttribute('class');
dataObj.description = event.target.getAttribute('description');
dataObj.code0 = event.target.getAttribute('code0');
dataObj.code1 = event.target.getAttribute('code1');
dataObj.code2 = event.target.getAttribute('code2');
event.dataTransfer.setData('Text',JSON.stringify(dataObj));
console.log("dragging");
};
Works in Chrome, Firefox gives me the following error:
ReferenceError: event is not defined
It points to the line with:
cedamed.handlers.dragElement(event);
I have come across 'solutions' that involved the originalEvent-property of the event api, which is often supposed to make everything work fine in FF, but it does not at all in my case. I made it work by setting the 'ondragstart'-attribute directly in the HTML, but shouldnt it work with 'jQuery.on'?
I'm sorry, there are several questions to this topic out there, but I just dont get whats going wrong in this field. Can you please give me an insight, whats wrong in here?
I found out I have to pass 'event' as an argument to the jQuery callback function in 'on' such as:
$(document).on('dragstart','.leistung', function(event){
cedamed.handlers.dragElement(event);
});
With usage of originalEvent in 'drageElement' I made it work finally. Sorry...

ExternalInterface return to AS3 not working consistently in IE

So, I'm having some trouble returning a value from an ExternalInterface call. I have a piece of code that looks like this:
var a:String = String(ExternalInterface.call("function() { var returnTest = 'test'; alert(returnTest); return returnTest;}"));
ExternalInterface.call("alert", a);
The first alert (in the anonymous function on line 1) is correct (obviously). However, the alert on line 2 is returning null 90% of the time in IE10. It works everytime in Firefox though.
To further explain the bit about working 90% of the time, it seems I can roll the dice again on whether or not it will work by adding or removing seemingly meaningless alerts. For example: let's say it's not working, I could add an alert and it will start working. Or, say it is working, I could add an alert for debugging, and it stops working, remove the alert, still doesn't work, add the alert back, and it starts working again. I know this isn't what's happening, but it's behaving as if a coin is flipped every time an alert is added or removed.
And this all only happens in IE, works perfectly every time in Firefox.
Thanks.
Edit:
The code I provided isn't the actual code that needs to work, but rather the code that I wrote to verify where the problem was. The actual situation is that there's a JavaScript property in the environment our Flash is running in that we need to know, but we don't have access to the HTML or JavaScript the SWF will be running in. The actual code I need to run looks more like this:
var pageNameFromJS:String = String(ExternalInterface.call("function() { var pageName = ServerObject.currentPage.name; alert(pageName); return pageName;}"));
ExternalInterface.call("alert", pageNameFromJS);
The alert in the first line is just to make sure that ServerObject.currentPage.name works, which it does. The alert in the second line is debug code that was added when we noticed that functions that require pageNameFromJS weren't working.
Really I dont know why you complicate things like this ;)
You can do it easier :
AS3 code:
ExternalInterface.addCallback("flash_function", flash_function);
function flash_function(from_js_param){
trace('param received from js : '+from_js_param)
}
ExternalInterface.call("js_function", to_js_param)
JS code:
function js_function(from_flash_param){
var to_flash_param = 'I received your '+from_flash_param;
(get_your_swf).flash_function(to_flash_param);
}

firebug (1.10.1) suggests javascript is not confined to a single thread in firefox (13.0)

While debugging some client side javascript today in Firefox, I ran into something that I found quite odd and little unnerving. Also, I was unable to duplicate this behavior while debugging the same script with IE / VS2010.
I created a simple example html document to illustrate the anomally I am seeing.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript" ></script>
</head>
<body id="main_body">
<script type="text/javascript">
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
</script>
<button class="test-trigger">test</button>
</body>
</html>
If you load this document into Firefox (I am using version 13.0 with Firebug version 1.10.1 on Windows 7), click test, and view the console tab in Firebug you should notice that the get request fails (cross domain violation that has nothing to do with the point I'm trying to make here), and then you will most likely see:
this will probably happen first.
this will probably happen second.
Now, place breakpoints on lines 13 and 20:
13: console && console.log && console.log("this will probably happen first.");
20: console && console.log && console.log("this will probably happen second.");
If you click test again you will break on line 13 as expected. Now, resume execution. If your experience is like mine, you will not break on line 20. Also if you switch to the console tab you will see the following sequence of log output:
this will probably happen second.
this will probably happen first.
To me, this suggests that the fail handler of the ajax request is being executed in a thread other than that which the click handler is being executed in. I have always been led to believe that all the javascript for a single page will be executed by a single thread in any browser. Am I missing something really obvious here? Thanks for any insight on this observation.
Oh, if I debug the same page running in IE using Visual Studio, both breakpoints are hit as I would expect.
I think it's safe to assume that the anomaly you're observing is caused by how Firebug implements breakpoints/works under the hood. I can't confirm that though. This also happens with FF 14 on OS X.
Unless jQuery immediately executes your fail() function and surpasses the whole XMLHttpRequest object, then there is a guarantee that the ordering of the statements will be this will probably happen first. then this will probably happen second..
Given the single threaded nature of JavaScript, functions will be essentially atomic; they will not get interrupted by a callback.
It seems as though you're trying to simulate what would happen if the click function takes a while to finish executing after calling loadStuff(). The click function shouldn't get interrupted by the fail method executing (mind == blown that you found a way to make that happen).
To take breakpoints out of the equation, here's a modified version. The rest of the markup is unchanged.
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
for (var i = 0; i < 1000000000; i++)
{
//block for some interesting calculation or something
}
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
The click function clearly takes a long time to execute, after calling loadStuff(), but the console will still reflect the correct order of the log statements here. Also worth noting, if you insert the same breakpoints, the ordering will be invalid, like the original example.
I'd file an issue for this with Firebug.
$.get("http://google.com/") is asynchronous, it is a race on what gets done first. The first time it is slower since it needs to make the call and the call happens later in the code execution. The call is already cached with the second request, so it happens to execute quicker.
If you need something to be done before the request goes out use beforeSend().
To my experience, Firebug doesn't work well when putting breakpoints in asynchronous code.
I.e. if you have one straight line of execution and put breakpoints in it, you'll be fine. However if you introduce asynchronicity e.g. by using setTimeout, you won't hit the breakpoint in that "parallel" line (which of course is not parallel really, the JS engine switches between the tasks). I've been experiencing it a lot in last couple of months.
In Chrome, it seems to work fine (they defer timeouts intelligently somehow). Perhaps because Chrome dev tools are built-in to the browser, it's easier to manipulate the timeouts. Firebug is "just" an add-on and perhaps it may be tricky to do it correctly.
A simple script to reproduce the issue:
Put breakpoints in lines when I assign value to x, y, z.
First, you'll hit a breakpoint on the line x = 1. Use F10 to step over. You won't hit a breakpoint on the line with z = 3 ever will hit a breakpoint on the line with z = 3 only if you're quick enough with pressing F10 (Firefox 14, Firebug 1.10).
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function foo(){
var x = 1;
setTimeout(bar, 2000);
var y = 2;
}
function bar(){
var z = 3;
}
foo();
</script>
</body>
</html>

variable assignments using jQuery failing in Safari?

I'm using jQuery 1.3.2 and it's breaking under Safari 4 for mysterious reasons.
All of my javascript references are made right before the tag, yet with the following code:
var status = $('#status');
status.change( function(){ /* ... */ } );
The following error is displayed in the Web Inspector:
TypeError: Result of expression 'status.change' [undefined] is not a function.
However the error is not encountered if I eliminate the variable assignment attach the change method directly like so:
$('#status').change( function(){ /* ... */ } );
Why? I need to use variables for this and several other findById references because they're used many times in the script and crawling the DOM for each element every time is regarded as bad practice. It shouldn't be failing to find the element, as the javascript is loaded after everything except and .
Try changing the variable to something other than "status."
It's confusing your variable with window.status (the status bar text). When I typed var status = $('#status') into the debugging console, the statusbar changed to [Object object]. Must be a bug in Safari.
If you put the code inside a function, so that status becomes a function-local variable, it should work.
It's standard practice in jQuery to wrap things in a
$.onready(function() {
});
This makes sure the DOM is loaded before you try to manipulate it.

Categories

Resources