javascript error console.log in Vertx Verticle - console.log

I expected my console.log statements in Javascript to appear in the terminal console of where I had started my verticle server but, it seems to be crashing..... (of course, on a client's browser it would play in the browser's console namely in Firefox - I would see it in the in built debugger - so analogously speaking it should appear on my terminals output because it is vertx's server side code execution of it's polygot rendering of javascript code)
This is the output of my running verticle in my bash terminal
Succeeded in deploying verticle
Exception in JavaScript verticle:
ReferenceError: "console" is not defined.
at file:/home/arjun/vertx_code/server.js:5 (anonymous)
at file:/opt/vert.x-2.1.3/sys-mods/io.vertx~lang-js~1.1.0/vertx/http.js:1847 (anonymous)
The javascript code that was used is the example install for a verticle from vertx.io
var vertx = require('vertx');
vertx.createHttpServer().requestHandler(function(req) {
req.response.end("Hello World!");
console.log("Reloaded");
}).listen(8080, 'localhost');
req.response.end("Hello World!");
console.log("Reloaded");
}).listen(8080, 'localhost');
Do I need another javascript package, do I need to do something along the lines of ...
var console = require('console');

Yes, you should require the console before you can use it.
So this should work:
var vertx = require('vertx');
var console = require('vertx/console');
vertx.createHttpServer().requestHandler(function(req) {
req.response.end("Hello World!");
console.log("Reloaded");
}).listen(8080, 'localhost');

Related

Running `.dart` files does not show logging messages

I just cannot figure out how to show logging messages when running dart files from terminal.
Example example.dart:
import 'dart:developer';
void main() {
print('print');
log('log');
}
Expected output:
print
log
Actual output:
print
I tried calling dart example.dart, dart run --all example.dart, dart run --verbosity=all example.dart, and different values instead of all (info, ...).
But non of these produced any helpful error messages let alone the out print I expect.
APIs from dart:developer (such as log) are intended to interact with debugging tools:
Interact with developer tools such as the debugger and inspector.
It's not explicit from the documentation for log, but I'd expect it to send a log message only to an attached debugger, not to the console.
If you want logging output that is independent of a debugger, use package:logging and add a listener that calls print, as shown by the example.

How can I prevent Chromium from writing to the console?

I'm making a very simple Delphi console application ({$APPTYPE CONSOLE}) with a single TChromiumWindow on the main form. The purpose of the application is to retrieve a webpage, process the HTML and output some JSON to the console. This can not be done using plain HTTP requests due to the nature of the webpage, which requires running some javascript as well.
Everything works as expected, except for one problem. The chromium components output some error messages to the console as well, which makes my JSON invalid! For example, I always get the following two error messages on startup:
[0529/133941.811:ERROR:gpu_process_transport_factory.cc(990)] Lost UI shared context.
[0529/133941.832:ERROR:url_request_context_getter_impl.cc(130)] Cannot use V8 Proxy resolver in single process mode.
Of course the best solution would be to not get any error messages in the first place, but for several reasons (which mostly have to do with company legacy code) I can't for example disable single process mode.
So the next best thing would be to keep these error messages from being printed to the console. I've tried setting
GlobalCEFApp.LogSeverity := LOGSEVERITY_DISABLE;
but that didn't help. Specifying a logfile using GlobalCEFApp.LogFile doesn't help either.
So how can I prevent the Chromium components from writing to the console at all?
The TChromium component provides an OnConsoleMessage event with signature :
TOnConsoleMessage = procedure(Sender: TObject; const browser: ICefBrowser;
const message, source: ustring; line: Integer;
out Result: Boolean) of object;
If you handle this event and set the Result variable to true the message output to the console is suppressed.
Set LogSeverity to LogSeverity.Fatal or n other desired.
var settings = new CefSettings()
{
//By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache"),
//Set log severity to showup only fatal errors.
LogSeverity = LogSeverity.Fatal,
};
//Autoshutdown when closing
CefSharpSettings.ShutdownOnExit = true;
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

how to do automated browser testing with Dart?

Is there any headless browser for dart? Or a wrapper for something like selenium? My goal is to use the browser for automated end-user testing for a website i wrote years ago. Now i need to make few changes on the site. Since it contains specific business logic, i would like to write some quick tests for the site without refactoring or modifying it for unit-tests, before i make those changes.
It seems like a fun introduction to get more familiar with dart ecosystem as well.
You can use Chrome or Dartium and drive it with ChromeDriver and the webdriver package
Here is a quick example:
import 'dart:convert';
import 'dart:io';
import 'package:webdriver/io.dart';
main() async {
// Start the ChromeDriver process
Process chromeDriverProcess = await Process
.start('chromedriver', ['--port=4444', '--url-base=wd/hub']);
await for (String browserOut in const LineSplitter()
.bind(UTF8.decoder.bind(chromeDriverProcess.stdout))) {
if (browserOut.contains('Starting ChromeDriver')) {
break;
}
}
// Connect to it with the webdriver package
WebDriver driver = await createDriver(
uri: Uri.parse('http://localhost:4444/wd/hub/'),
desired: Capabilities.chrome);
// Go to your page
await driver.get('http://stackoverflow.com');
//TODO: write your tests
print(await driver.execute('return navigator.userAgent', []));
// Take a simple screenshot
String screenshot = await driver.captureScreenshotAsBase64();
new File('stackoverflow.png').writeAsBytesSync(BASE64.decode(screenshot));
driver.quit();
chromeDriverProcess.kill();
}
It is not totally "headless" but it is easy to make it work on server like Travis-CI with this config:
before_install:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
content-shell is a headless browser with Dart support like Dartium
(https://www.dartlang.org/install/mac)
and https://pub.dartlang.org/packages/webdriver can be used for Selenium test.
There is headless support for Chromium work-in-progress. When Dartium is upgraded to use this Chromium version, Dartium should be able to be run headless.
The Dart team is working on incremental JS compilation (DDC - Dart development compiler) which should allow to use Chrome as development browser. The headless mode (when available) can be used directly.
Depending on your use case and requirements, you might also be able to use puppeteer
For example (from the docs), you can take a screenshot of the page
void main() async {
// Start the browser and go to a web page
var browser = await puppeteer.launch();
var page = await browser.newPage();
// Setup the dimensions and user-agent of a particular phone
await page.emulate(puppeteer.devices.pixel2XL);
await page.goto('https://dart.dev', wait: Until.networkIdle);
// Take a screenshot of the page
var screenshot = await page.screenshot();
// Save it to a file
await File('example/_github.png').writeAsBytes(screenshot);
await browser.close();
}
You can also generate a PDF, take a screenshot of a node, interact with the page, evaluate JavaScript, and use the results from your Dart code, and more.

Firefox native messaging through webextension

Created a webextension for firefox (currently using Nightly 52), that uses native messaging to launch a java program on Linux (Ubuntu 14, 32x).
The webextension loads, reads the .json file and reads the path which points to a script that starts the java program. The JSON and the path are correct as when I use:
var native = browser.runtime.connectNative("passwordmanager");
console.log("native.name" + native.name); //outputs passwordmanager.
native.onDisconnect.addListener(function(m) { console.log("Disconnected"); });
The above code prints the name of the native port and also prints "Disconnected". So I m guessing the native app is terminating for some reason.
The application is only skeleton right now, that just does sysout and reads sysin and works correctly if Launch it directly through the shell script.
While debugging the webextension, I am not able to step into the call to connectNative, as it just steps-over that call instead of doing step-in. So kind of out of options whats' going wrong.
Please let me know if anyone is able to create a native messaging app based on FF webextension and any pointers on what I might be doing wrong.
Thanks
This solution here shows you how to detect onConnect and onFail. It should help you out to figure out your real problem.
So I don't think you can do proper error handling with connectNative from the JS side alone. You can do somewhat error handling if you get the exe side involved, but you can't get a string for "error reason" when an error occurs. The error is only logged to console.
First make sure to set your deeloper prefs, so messages show in your browser console. You can use this addon - https://addons.mozilla.org/en-US/firefox/addon/devprefs/ - or read that addon description it gives you the MDN page with the prefs to set.
Then this is how you can do some sort of error handling (without error reason) (pseudo-code - i might need a .bind in the callbcks):
function connectNative(aAppName, onConnect, onFail) {
var listener = function(payload) {
if (!connected) {
connected = true;
port.onDisconnect.removeListener(failedConnect);
onConnect();
} else {
// process messages
}
}
var failedConnect = function() {
onFail('failed for unattainable reason - however see browser console as it got logged there');
}
var connected = false;
var port = chrome.runtime.connectNative(aAppName);
port.onMessage.addListener(listener);
port.onDisconnect.addListener(failedConnect);
return port;
}
Now in your exe, as soon as it starts up, make it write to stdout something. That will trigger the onConnect.

How can I make a firefox add-on contentscript inject and run a script before other page scripts?

I'm working on a Browser extension/add-on. We have it working in Chrome, so I'm trying to get it working in Firefox.
I've gotten my add-on to load in Firefox Developer Edition 49.0a2 (2016-07-25).
My extension involves a content_script set to run_at: document_start, so it can inject a script tag before other page scripts run, so it can make an object globally available to websites.
This has seemed to work fine in Chrome, but in Firefox it has proven to be a bit of a race condition, with other page resources loading first most of the time.
Is there a strategy to load a content script in a way that it can inject & load a script before any other page scripts run?
When I add logs, I can isolate what is happening pretty nicely. In this example content-script:
// inject in-page script
console.log('STEP 1, this always happens first')
var scriptTag = document.createElement('script')
scriptTag.src = chrome.extension.getURL('scripts/inpage.js')
scriptTag.onload = function () { this.parentNode.removeChild(this) }
var container = document.head || document.documentElement
// append as first child
container.insertBefore(scriptTag, container.children[0])
Now if the file scripts/inpage.js simply runs a log, like
console.log('STEP 2, this should always run second')
And I visit a page with a script like this:
console.log('Step 3, the page itself, should run last')
In practice, Step 2 and Step 3 run in a non-deterministic order.
Thanks a lot!
I have Firefox-compatible version of the script in a public repository on a special branch if you dare to try it yourself: https://github.com/MetaMask/metamask-plugin/tree/FirefoxCompatibility
An dynamically inserted script with an external source (<script src>) does not block the execution of scripts, so there is no guarantee that your script would load. If your extension worked in Chrome, it was just by sheer luck.
If you really want to run some script before the rest, you have to run it inline:
var actualCode = `
// Content of scripts/inpage.js here
`;
var s = document.createElement('script');
s.textContent = actualCode;
(document.head || document.documentElement).appendChild(s);
s.remove();
Ideally, your build script would read scripts/inpage.js, serialize it to a string and put it in the actualCode variable. But if inpage.js is just a few lines of code, then the above can be used.
Note that you should not inject code in the web page unless it is absolutely necessary. The reason for that is that the execution environment of the page is untrusted. If you inject at document_start, then you can save functions and (prototype) methods that use for later (in a closure), but very careful coding is required.
If your content script is not generated by a build script and you still want to keep the scripts separate, then you can also use synchronous XMLHttpRequest to fetch the script. Synchronous XHR is deprecated for performance reasons, so use it at your own risk. Extension code is typically bundled with your extension, so the use of sync xhr should be low-risk:
// Note: do not use synchronous XHR in production!
var x = new XMLHttpRequest();
x.open('GET', chrome.runtime.getURL('scripts/inpage.js'), false);
x.send();
var actualCode = x.responseText;
var s = document.createElement('script');
s.textContent = actualCode;
(document.head || document.documentElement).appendChild(s);
s.remove();
If you are using a bootstrap.js based addon you can use a framescript and DOMWindowCreated to work with the document before even the HTML DOM (past basics of document.body etc) renders - https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox/Frame_script_environment#Events - the innerHTML will be available but no script would have executed. You can put your inline script at the top as #Rob mentioned.

Resources