"Browser is not defined" error when running firefox sample extension - javascript

I have 60.4.0esr (64-bit) installed in by GNU/Linux system. When running the find-across-tabs extension I am getting the error
ReferenceError: browser is not defined[Learn More]
find.js:1:5
<anonymous>
file:///home/username/webextensions-examples-master/find-across-tabs/find.js:1:5
I am able to run extensions like borderify correctly

I think the error is quite clear. The issue here is
ReferenceError: browser is not defined
in the:
let backgroundPage = browser.extension.getBackgroundPage();
They are probably referencing the mozilla.org docs. You can test the examples there to see if you are getting an error or not.
You can run the function directly in popup. In example:
Suppose a background script defines a function foo():
// background.js
function foo() {
console.log("I'm defined in background.js");
}
A script running in a popup can call this function directly like this:
// popup.js
var page = browser.extension.getBackgroundPage();
page.foo(); // -> "I'm defined in background.js"
NOTE: The question is if you are not using private browsing mode as this function can't use with it. This is due to this bug. It will always return null.

Related

Why getting "Uncaught ReferenceError: $ is not defined" error on Chrome Dev Console?

I'm trying to run a simple JQuery script in Chrome Developer Console but I have a problem.
There is no problem in this code when I run it on Chrome Developer Console:
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
But, I'm getting an error when try to run the same code inside a setTimeout function like below:
setTimeout(function(){
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
}, 1000);
Uncaught ReferenceError: $ is not defined
Not only does this happen in setTimeout function, it happens in a normal function as well.
I'm working with latest version of Google Chrome. How can I use JQuery like above in a setTimeout function?
The confusion here is centered on the fact that $ is part of Chrome's Command Line API. When you use $ in your code, you're referring to the Command Line API function named $. You are probably not loading jQuery at all: indeed, your someValue !== null code wouldn't even work with jQuery anyway. You'd need to test for a non-empty jQuery object (someValue.length > 0), not a non-null.
As for why Chrome's $ is accessible in the console but not a setTimeout callback: this appears to be engine-specific magic that limits the command line API to console code only. setTimeout executes its callback in such a way that Chrome cannot be sure the code originated from the console, so it does not grant access to the command line API function named $. Curiously, this isn't typical of JavaScript. Using normal JavaScript scoping rules, the setTimeout callback should have access to the same variables as the surrounding code, regardless of when and where it's executed. The fact that the scope is different one second later is very surprising -- you are right to feel confused!
As a curiosity, a way to simulate this in vanilla JavaScript would be with an object-based scope via with that mutates after the command completes. For example, if every snippet you typed into the console were wrapped with:
var chromeConsoleAPI = { $: function() { ... } }
with(chromeConsoleAPI) {
// your snippet here
}
delete chromeConsoleAPI.$;
In this case, $ is supplied by accessing the chromeConsoleAPI object on the scope chain. Normal code can access $, but since the setTimeout function runs after chromeConsoleAPI.$ is deleted, it does not find anything named $. Note that this still doesn't completely replicate the behavior, because this blocks access to any user-defined $. In actuality, the command line API must inject its functions at the very top (i.e., most remote) part of the scope chain.
The problem because Jquery library Load after your custome code loaded.
Are you using external js file for your custome script?
Then you load your script under the jquery script.
You must add jquery library link first then add your script.

Getting the stack trace of a console message

Sometimes I see stray log statements when I load up my application, and I don't remember how the log statement was called. Is there a way to find the stack trace of a console log message from the Chrome developer tools?
Right now, I wrap console.log with a function that prints the stack trace:
console.log = (function () {
var oldLog = console.log.bind(console);
return function () {
try { throw new Error(); } catch (e) {
oldLog(
e.stack.split('\n')
.slice(2)
.map((line) => line.trim().replace('at', 'from'))
.join('\n')
);
}
oldLog.apply(null, Array.prototype.slice.call(arguments));
};
}());
This will print the stack trace in addition to the log message. For this to be useful, I have to insert this code just before any of my code runs. Is there a way to find out this information from just the console, without having to add this wrap?
I primarily use Chrome developer tools, but I'd be interested if this was possible in any other browser.
Have you tried console.trace()? It is available in Chrome and Firefox. For your use-case, you could alias log to trace.
That said, I usually wrap logger statements in a custom logger function that itself wraps whatever I need to use, but which can be programmatically disabled in production to prevent leaking logs.
EDIT:
There aren't currently any chrome://flags that would let you set that behaviour, but you could do this before your console gets invoked (such as at the top of your minified js): console.log=console.trace;
Which will have this effect, (example in Chrome Canary's console):
> console.log("Hello, Robz");
VM929:2 Hello, Robz
undefined
> console.log = console.trace;
function trace() { [native code] }
> console.log("Hello, Robz");
VM935:2 Hello, Robz
VM935:2 (anonymous function)
VM468:777 InjectedScript._evaluateOn
VM468:710 InjectedScript._evaluateAndWrap
VM468:626 InjectedScript.evaluate
Basically. To show the source of a logging-message was a very bad idea. It leads you to write logging messages that neither belongs to the code nor can be localized without a stack-trace.
How do you work in a Team with it?
hey, i got a `ohoh!`-logging in file abc.js in line 3487!
To understand the problem by inspecting the call-stack means: Hey i do not need a text-message, i do not need a message what exactly is going on, just where.

Style console.log output and run functions

After having a little snoop around the source code for http://pinterest.com, I noticed how they use the console to communicate with users (Appears to only work in Chrome).
Also, if I enter joinUs() on the console log, a function is run which directs me to a new page.
I attempted to run a function within the console log on my own website by declaring a function:
function testFunc(){
console.log('Hello world!');
}
But if I try entering testFunc() on the console log, I get the following error:
ReferenceError: testFunc is not defined
Does anybody have any information on how to style the output of the console log, and how to run a function from within the console?
For styling, you could check https://github.com/adamschwartz/log
If you read through the code I'm sure you can figure out how it works.
As for having testFunc available, try explicitly assigning it to window, so do window.testFunc = function () { console.log('Hello world!') };. That should work.

(after) jquery get script success I don't see (deliberate) errors

I don't understand why I cant see errors from my script after success (I google this and it just comes up with lots of answers about error handling for the event of success/error on jquery get script).
If I do this with 'any' js script
$.getScript('myextrascript.js',function(){console.log('got it!');});
Emphasis on 'any' js script (I've tried at least 12 different scripts by different people) because after my script had an error that just stopped the script (I got no console error) my first thought was does this happen just with my code?
say for example my extra script had a deliberately undeclared variable in it...
myextrascript.js:
console.log('I can see this in the console no problem');
var declaired='this variable is ok';
undeclaired='this will cause an error';
console.log("I now don't see this console log because my code has stopped");
I would normally see the error in the console like
undeclaired is undefined myextrascript.js:3
But I don't see errors inside my extra scripts, Not even if I put this a line before my error
window.onerror=function(e,script,line){window.console.log("Error: "+e+" ("+script+":"+ line+")");}
Don't really have anymore ideas past this, It's really puzzling.
Solved!
"use strict";
window.onerror=function(e,script,line){window.console.log("Error: "+e+" ("+script+":"+ line+")");}
undeclaired=1;
console.log('WINNING!');
I added "use strict"; and now it its working/broken (BROKEN JUST HOW I WANT!)
Error: Uncaught ReferenceError: undeclaired is not defined (myextrascript.js:12)
Uncaught ReferenceError: undeclaired is not defined

How can I override/extend ReferenceError in Chrome's JavaScript?

To make debugging easier, I'm capturing all of the console logs in Chrome so that users who submit a feedback entry will also submit all of the logs to our server. When someone encounters a problem in production, I can first and foremost get them back to work so that I can then sit down and more thoroughly go through all of the logs to determine the root cause of whatever issue the user encountered in production.
The technique I use to capture the logs involves overriding console.log so that all text entered in the first argument gets stored in an array while simultaneously invoking the legacy function so that I can still see the logs in the console too.
The problem is when there's the occasional uncaught exception. These aren't included in the uploaded logs, so it's not always clear what caused the problem. So I tried overriding ReferenceError by writing a JavaScript function that takes a function as an argument, then returns a new function that does stuff with it, like storing data in a variable, and then invoking the legacy function as the last step:
function overrideException(legacyFn) {
/** arguments for original fn **/
return function() {
var args = [];
args[0] = arguments[0];
// pass in as arguments to original function and store result to
// prove we overrode the ReferenceError
output = ">> " + legacyFn.apply(this, args).stack;
return legacyFn.apply(this, arguments);
}
}
To test the overrideException function, I ran the following code on the console:
ReferenceError = overrideException(ReferenceError);
Afterwards, I tested the returned function, the new ReferenceError, by manually throwing a ReferenceError:
throw new ReferenceError("YES!! IT WORKS! HAHAHA!");
The resulting output on the console is:
ReferenceError: YES!! IT WORKS! HAHAHA!
And checking the global variable output from the overrideException function shows that it did indeed run:
output
">> ReferenceError: YES!! IT WORKS! HAHAHA!
at ReferenceError (<anonymous>)
at new <anonymous> (<anonymous>:18:35)
at <anonymous>:2:7
at Object.InjectedScript._evaluateOn (<anonymous>:562:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:521:52)
at Object.InjectedScript.evaluate (<anonymous>:440:21)"
Now, here's where things start to fall apart. In our code, we're not going to know when an uncaught exception occurs, so I tested it by attempting to run a function that doesn't exist:
ttt();
Which results in:
ReferenceError: ttt is not defined
However, unlike the case where we explicitly throw an error, in this case, the function doesn't fire, and we're left with only the legacy functionality. The contents of the variable output is the same as in the first test.
So the question seems to be this: How do we override the ReferenceError functionality that the JavaScript engine uses to throw errors so that it's the same one we use when we throw a ReferenceError?
Keep in mind that my problem is limited only to Chrome at this time; I'm building a Chrome Packaged app.
I have done quite a bit of research for the same reason: I wanted to log errors and report them.
"Overriding" a native type (whether ReferenceError, String, or Array) is not possible.
Chrome binds these before any Javascript is run, so redefining window.ReferenceError has no effect.
You can extend ReferenceError with something like ReferenceError.prototype.extension = function() { return 0; }, or even override toString (for consistency, try it on the page, not the Dev Tools).
That doesn't help you much.
But not to worry....
(1) Use window.onerror to get file name, 1-indexed line number, and 0-indexed position of uncaught errors, as well as the error itself.
var errorData = [];
onerror = function(message, file, line, position, error) {
errorData.push({message:message, file:file, line:line, position:position, error:error});
};
See the fiddle for an example. Since the OP was Chrome-specific, this has only been tested to work in Chrome.
(2) Because of improvements to (1), this is no longer necessary, but I leave this second technique here for completeness, and since onerror is not guaranteed to work for all errors on all browsers. You will also sometimes see the following:
var errors = [];
function protectedFunction(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
errors.push(e);
throw e;
}
};
}
setTimeout = protectedFunction(setTimeout);
setInterval = protectedFunction(setInterval);
etc...
FYI, all this is very similar to what has been done in the Google Closure Compiler library, in goog.debug, created during Gmail development with the intent of doing exactly this. Of particular interest is goog.debug.ErrorHandler and goog.debug.ErrorReporter.

Categories