Git Product home page Git Product logo

node-webkitgtk's Introduction

node-webkitgtk

⚠️ deprecated - see express-dom version >= 6 to prerender web pages using playwright.

Pilot webkitgtk from Node.js with a simple API.

Also offers a command-line REPL, able to display (or not) the current window, output pdf or png, see webkitgtk --help, and several example calls in examples/repl.sh.

Falls back to jsdom if the module cannot be compiled (with obvious limitations like inability to render the DOM nor output png or pdf).

Typically, express-dom can run on webkitgtk's jsdom mode - developers can work on other platforms where jsdom builds fine.

this module uses only system-installed, shared libraries it doesn't embed static libraries, meaning it plugs very nicely into system-installed libraries.

Node.js compatibility

Node.js LTS and Current.

usage

The API has two styles:

  • with callbacks, all methods return current instance
  • without callbacks, all methods return promise

For convenience, the returned promises have bound methods once, on, when.

These calls will output pdf/png version of fully loaded pages (see documentation below about idle event).

Pdf output from cli:

webkitgtk --pdf test.pdf \
 --paper 210x297 \
 --margins 20,20,20,20 \
 --unit mm \
 http://google.fr

Png output from cli:

webkitgtk --png test.png http://nasa.gov
var WebKit = require('webkitgtk');
var fs = require('fs');

// optional, if nothing is set, defaults to :0
var displayOpts = {
  width: 1024,
  height: 768,
  display: "99"
};


// old-style creation
var view = new WebKit();
view.init(displayOpts).then(function() {
  view.load(uri, {
    style: fs.readFileSync('css/png.css') // useful stylesheet for snapshots
  })
  view.when('load', function() {
    return this.png('test.png');
  });
});

// short-hand can init display and load
WebKit.load(uri, {
  display: displayOpts, // optional, defaults to :0
  style: fs.readFileSync('css/png.css') // useful stylesheet for snapshots
}).once('idle', function() {
  this.png('test.png'); // this is always the created instance in listeners
  // ...
});

A facility for choosing/spawning a display using xvfb

// this spawns xvfb instance
// new-style creation
WebKit("1024x768x16:99", function(err, w) {
  w.load("http://github.com", function(err) {
    w.png('test.png', function(err) {
      // done
    });
  });
});

// this uses a pre-existing display
WebKit(98, function(err, w) {
  w.load("http://google.com");
});

// use pre-existing display 0 by default
Webkit(function(err, w) {
  w.load("http://webkitgtk.org", function(err) {
    w.html(function(err, str) {
      console.log(html);
    });
  });
});

Asynchronous (life) event handlers

WebKit
.load("http://localhost/test", {content: "<html><body></body></html>"})
.when("ready", function(cb) {
  this.run(function(className, done) {
    setTimeout(function() {
      document.body.classList.add(className);
      done();
    }, 100);
  }, 'testClass', cb);
})
.when("ready", function(cb) {
  setTimeout(cb, 100);
})
.when("idle", function() {
  // promise variant
});

See test/ for more examples.

use cases

This module is specifically designed to run 'headless'. Patches are welcome for UI uses, though.

  • snapshotting service (in combination with 'gm' module)

  • print to pdf service (in combination with 'gs' module)

  • static web page rendering

  • long-running web page as a service with websockets or webrtc communications

  • gui widgets (since webkitgtk >= 2.7.4, transparent windows are possible), see the github wiki of node-webkitgtk.

load(uri, opts, cb) options

  • WebKitSettings Some settings have different default values: enable-plugins: FALSE enable-html5-database: FALSE enable-html5-local-storage: FALSE enable-java: FALSE enable-page-cache: FALSE enable-offline-web-application-cache: FALSE default-charset: "utf-8" user-agent: backend-specific value

  • deprecated WebKitSettings aliases: private: enable-private-browsing images: auto-load-images localAccess: allow-file-access-from-file-urls ua: user-agent charset: default-charset

  • cookies string | [string], default none note that as of webkitgtk 4.3.3 cookies are properly cleared and isolated between views.

  • width number, 1024

  • height number, 768 the viewport

  • allow "all" or "same-origin" or "none" or a RegExp, default "all" A short-hand filter that is run after all other filters. Note that data:uri are discarded by "none" and allowed by "same-origin".

  • filters An array of request filters that are run in browser, synchronously. All filters are called one after another, and each filter can read-write the following properties on this: uri (string) cancel (boolean) ignore (boolean) and has read-only access to from (string, in case the uri was redirected from another uri) In particular, a filter can revert the action of a previous filter. The initial document loading request is not filtered. A single filter is either a function() {}, or an array [function(arg0, ...) {}, arg0, ...], allowing passing immutable stringyfiable arguments to the filter function.

  • filter Convenient option to append one filter to the list in opts.filters.

  • navigation boolean, default false allow navigation within the webview (changing document.location).

  • dialogs boolean, default false allow display of dialogs.

  • content string, default null load this content with the given base uri.

  • script buffer, string or {fn: function(..args) {}, args: [..]}, default null insert script at the beginning of loaded document. args length must match fn function arity.

  • scripts same as script but an array of them, default []

  • style string, default null insert user stylesheet

  • transparent boolean, default false webkitgtk >= 2.7.4 let the background be transparent (or any color set by css on the document)

  • decorated boolean, default true show window decorations (title bar, scroll bars)

  • timeout number, default 30000 timeout for load(), in milliseconds

  • stall number, default 1000 requests not receiving data for stall milliseconds are not taken into account for deciding idle events.

  • stallInterval number, default 1000 wait that long before ignoring all setInterval tasks as idle condition. Set to 0 to ignore all.

  • stallTimeout number, default 100 wait that long before ignoring all setTimeout tasks with timeout > 0 as idle condition. Tasks with 0 timeout will not be ignored, though. Set to 0 to ignore all.

  • stallFrame number, default 1000 wait that long before ignoring requestAnimationFrames as idle condition. Set to 0 to ignore all.

  • console boolean, default false Send console events (see below). Default listener outputs everything and is disabled by registering a custom listener.

  • runTimeout number, default 10000 Async run() calls will timeout and call back after runTimeout ms. Sync run() calls, or runev() calls, are not affected. Can be disabled by setting this param to 0.

init(opts, cb) options

init(display) can be called instead of passing an object.

  • display number for port, or string, (WIDTHxHEIGHTxDEPTH):PORT, default env.DISPLAY checks an X display or framebuffer is listening on that port init(display)

  • width number, 1024

  • height number, 768 Framebuffer dimensions

  • depth number, 32 Framebuffer pixel depth

  • offscreen boolean, default true By default, nothing is shown on display. Set to false to display a window.

  • resizing boolean, default false Set to true to allow window.moveTo/resizeTo (and moveBy/resizeBy) to be handed over to the window manager (which might ignore the requests). (New in version 4.8.0)

  • verbose boolean, default false log client errors and stalled requests, otherwise available as DEBUG=webkitgtk:timeout,webkitgtk:error.

  • cacheDir string, $user_cache_dir/node-webkitgtk path to webkitgtk cache directory. Changing cacheDir can fail silently if webkitgtk lib is already initialized.

  • cacheModel string, defaults to browser. none: disables cache completely local: cache optimized for viewing local files browser: the real deal

  • debug boolean, default false shows a real window with a web inspector. As a commodity, *the inspector must be closed- to get the idle event fired.

  • cookiePolicy string, "always", "never", any other string defaults to "no third party".

If width, height, depth options are given, an xvfb instance listening given display port will be spawned using headless module. Wrapping the application with xvfb-run command line tool is a safe(r) alternative.

pdf() options

If you plan to author html pages for printing, i strongly suggest to set an html document width in pixels equal to the paper width at 144 dpi (example: 1190px for iso_a4 portrait). Also never forget that 1in = 2.54cm = 25.4mm = 72pt = 6pc. See Units

  • orientation landscape | portrait, default to portrait

  • paper (string) typical values are iso_a3, iso_a4, iso_a5, iso_b5, na_letter, na_executive, na_legal, see GTK paper size.

  • paper (object) unit : string, mm|in|pt, default "pt" width : number, default 0 height : number, default 0

  • margins (number) sets all margins in "pt" units, default 0

  • margins (string) sets all margins in given units, default 0 and "pt"

  • margins (object) unit : string, mm|in|pt, default "pt" left, top, right, bottom : number, default 0

events

All events are on the WebKit instance.

These are lifecycle events:

  • ready same as document's DOMContentLoaded event

  • load same as window's load event

  • idle when all requests (xhr included), timeouts, intervals, animation requests, are finished or timed out (see stall- options).

  • unload same as window's unload event

These events happen once and in that order.

A new busy event can happen after idle event: it tracks further activity after idling state, caused by any of:

  • setTimeout is finished or cleared
  • setInterval is finished or cleared
  • xhr is finished or aborted
  • animationFrame is finished or cancelled
  • a websocket emits a message

It can be used to track updates done by XHR, or long timeouts executed after page load.

Registering a listener for an event that already happened immediately calls the new listener.

These events can happen at any moment:

  • error this is what is caught by window.onerror listener(message, url, line, column)

  • request listener(req) where req.uri, req.headers are read only. The request has already been sent when that event is emitted.

  • response listener(res) res have read-only properties uri, mime, status, length, filename, headers. res.data(function(err, buf)) fetches the response data.

  • data listener(res), called as soon as the first chunk of data is received. res have read-only properties uri, mime, status, length, filename, headers, and clength - the length of the received chunk of data.

  • authenticate listener(request) where request.host, request.port, request.realm are read-only. request.use(username, password) authenticates request.ignore() ignores authentication Both methods can be called later (asynchronously), but at least one of them is supposed to be called if the signal is handled.

  • navigate listener(url) Called when document location changes (not when history state change). Navigation is permitted or not using navigation option, not this event.

  • console (deprecated) listener(level, ...) where level is 'log', 'error', 'warn' or 'info'. Remaining arguments are the arguments of the corresponding calls to console[level] inside the page. Logging everything that comes out of web pages can be annoying, so this is disabled by default. This event is deprecated - use console load option to enable/disable console output instead.

  • crash (since version 4.9.0) When the underlying web view has crashed. It's a good idea to destroy it and use a new one.

methods

  • new Webkit() creates an unitialized instance upon which init() must be called. WebKit is also an EventEmitter.

  • WebKit(opts?, cb) Same as above. If arguments are given, equals new WebKit().init(opts, cb).

  • init(opts?, cb) see parameters described above must be invoked before (pre)load. Callback receives (err, instance).

  • clearCache() Clear cache of the current instance. Busy on-disk resources won't be cleared, so it's safer to call on an unloaded view. Other running instances sharing the same cache may not be immediately affected.

  • preload(uri, opts?, cb) load uri into webview initial scripts are not run, resources are not loaded. These options are not effective: cookies, script, allow. Callback receives (err, instance).

  • load(uri, opts?, cb) load uri into webview see parameters described above. Callback receives (err, instance).

  • once(event, listener) the standard synchronous EventEmitter interface

  • when(event, asyncListener*) Allow queuing asynchronous jobs on an event and before next event. The async listener can have a function length of zero, in which case it is considered to be a thenable; and the method returns the promise. If asyncListener is missing it returns the latest promise. Using promises is the only way to catch errors from previous jobs. Otherwise the callback-style API is assumed.

  • run(sync-script, param*, cb) any synchronous script text or global function. If it's a function, multiple parameters can be passed, as long as they are serializable.

  • run(async-script, param*, cb) async-script must be a function with callback as last argument, whose arguments will be passed to cb, as long as they are stringifyable.

  • runev(async-script, param*, cb) async-script must be a function, it receives an emit function as last argument, which in turn acts as event emitter: each call emits the named event on current instance, and can be listened using view.on(event, listener). The listener receives additional arguments as long as they're stringifyable. Can be used to listen recurring events.

  • png(writableStream or filename, cb) takes a png snapshot of the whole document right now. If invoked with a filename, save the stream to file. Tip: use custom css to cut portions of the document.

  • html(cb) get the whole document html, prepended with its doctype, right now. Callback receives (err, str).

  • pdf(filepath, opts?, cb) print page to file right now see parameters described above.

  • reset(cb) Stops loading if it was, unregister listeners, allows .load() to be run sooner than when calling unload.

  • unload(cb) Sets current view to an empty document and uri. Emits 'unload' event.

  • destroy(cb) does the reverse of init - frees webview and xvfb instance if any. init() can be called again to recover a working instance. destroy must be called after unload to avoid memory leaks.

properties

  • WebKit.navigator static property, a copy of the currently installed engine.

  • uri Read-only, get current uri of the web view.

  • readyState Read-only: empty, "opening", "loading", "interactive", "complete" Before the first call to .load(uri, cb) it is empty, and before cb is called it is opening.

debugging

DEBUG=webkitgtk node myscript.js to print all logs.

In a production environment, it could be useful to set the init option verbose = true or, equivalently, the environment variables DEBUG=webkitgtk:timeout,webkitgtk:error,webkitgtk:warn

This will keep the page running, output console to terminal, and open a gtk window with inspector open:

WebKit({debug: true, verbose: true}, function(err, w) {
  w.load(url, {console: true});
});

For debugging of node-webkitgtk itself, please read ./DEBUG.

about plugins

Update: webkit2gtk >= 2.32 no longer loads those plugins

In webkit2gtk >= 2.4.4, if there are plugins in /usr/lib/mozilla/plugins they are initialized (but not necessarily enabled on the WebView), and that could impact first page load time greatly (seconds !) - especially if there's a java plugin.

Workaround: uninstall the plugin, on my dev machine it was /usr/lib/mozilla/plugins/libjavaplugin.so installed by icedtea.

install

Linux only.

Compatible with webkitgtk (WebKit2) versions 2.8 and above.

It's usually a better idea to use latest stable webkit2gtk.

These libraries and their development files must be available in usual locations.

  • webkit2gtk-3.0 (2.4.x), for node-webkitgtk 1.2.x
  • webkit2gtk-4.0 (>= 2.8.x), for node-webkitgtk >= 1.3.0
  • glib-2.0
  • gtk+-3.0
  • libsoup2.4

Also usual development tools are needed (pkg-config, gcc, and so on).

On debian/jessie, these packages will pull necessary dependencies:

  • nodejs
  • npm
  • libwebkit2gtk-3.0-dev (2.4.x), for node-webkitgtk 1.2.x
  • libwebkit2gtk-4.0-dev (>= 2.8.x), for node-webkitgtk >= 1.3.0

On fedora/21:

  • nodejs
  • npm
  • webkitgtk4-devel

On ubuntu/14: try the WebKit team ppa

License

MIT, see LICENSE file

node-webkitgtk's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-webkitgtk's Issues

Requests after readyState goes to idle or complete

Hey there!

I'm having an issue with requests that are made after webview.readyState goes to complete, and async requests are not being fired off.

That usually happens with javascript that creates more requests within itself.

Please have a look at the script below:

var Webkit = require('webkitgtk');

var url        = 'http://d3s84xo5cmutkt.cloudfront.net/renders/attachments/000/011/601/original/latest_just-map.html';
var portView   = { width: 567, height: 756 }; // Pixels
var requests   = 0;

var webview = Webkit();

webview.load(url, portView);

webview.on('request', function (request) {
  requests += 1;
  console.log('# Counter on request: ' + requests + ', state is: ' + webview.readyState);
  console.log('# URL: ' + request.uri);
});

webview.on('response', function (response) {
  requests -= 1;
  console.log('# Counter on response: ' + requests + ', state is: ' + webview.readyState);

  if (requests === 0) {
    console.log(webview.readyState);
    printPdf();
  }
});

webview.on('busy', function() {
  console.log("##### STILL BUSY!");
});

webview.on('console', function (level, message) {
  // console.log("\n## Console log: " + JSON.stringify(message) + "\n");
});

function printPdf() {
  console.log("Rendering PDF. State: " + webview.readyState);

  var filename  = 'renders/output.pdf';
  var paperSize = { paper: { width: 150, height: 200, unit: 'mm' } };

  webview.pdf(filename, paperSize, function(err) {
    if (err) {
      webview.destroy();
      console.log(err.toString());
    }

    console.log('Render done!');
    webview.destroy();
  });
}

It should only render when the requests counter reaches zero. However, one of the calls to openmaps performs other async calls to each of the map tiles. It's possible to see that with Chrome:
chrome

From what I understood after digging into webkitgtk.js file:

  • It goes to idle and no more requests are performed, unless loop.call(this, true) is called again.
  • I tried debug: true so that priv.inspecting is true, therefore this code would never get executed.
  • I get the requests happening, and I can see it because the script listens to webview.on('request').

The problem I see here is: I'm not able to count requests with the script either because the counter reaches zero before the next async request is made, therefore the pdf function being called when not all requests were actually loaded, or sometimes being called twice as the counter increments/decrements again, going to zero twice or more.

I'm not entirely sure either it is a bug on node-webkitgtk or I'm not treating that with my script in the right way. I'd appreciate if you could shed some light for me.

If you need more clarification, please let me know.

Cheers

idle event should be emitted after every time some activity has been detected

This would allow stuff like

var inst = W().load(url);
(function hadActivity() {
  inst.wait('idle', function(err) {
    // do something
    setImmediate(hadActivity);
 });
})();

So an export of a living instance (typically plugged to a socket.io server) could be updated each time it changes in any way.

Figure a way to decide what is "some activity" !
A non-idling event loop seems a little too fuzzy to detect activity.

Using Linux FB

Hi, is there a way to use the Linux FB with this module ? Do I have to switch out your GTK version with GTK-fb or is there an other thing to do?

Segfault on `pdf` when `fullpage: true`

First, thanks for the awesome project. Looks super cool and we're very excited about being able to use it.

We're running into a little trouble when using the fullpage true option.

Semi related, do you have any suggestions about setting the paper size programmatically when printing to PDF?

> var WebKit = require('webkitgtk');
> WebKit('99').load('http://google.com').wait('idle').pdf('testing.pdf', { fullpage: true });
{ priv:
   { state: 0,
     pendingRequests: 0,
     loopForCallbacks: 0,
     loopForLife: false,
     loopCount: 0,
     idleCount: 0,
     ticket: 0,
     tickets: {},
     eventName: 'webkitgtk1416381062693',
     loopTimeout: null,
     loopImmediate: null,
     wasBusy: false,
     wasIdle: false,
     previousEvents: {} },
  chainState: { ready: true, idle: true } }
>
(nodejs:21011): Gtk-WARNING **: Unsupported unit
[1]    21011 segmentation fault (core dumped)  nodejs

The library halts on an invalid URL

When using the load function and providing an URL like this: "www.github.com" (without http://)

.load(href, loadParams, cb);

the library halts with the following error

** (node:4571): CRITICAL **: gchar* webkit_favicon_database_get_favicon_uri(WebKitFaviconDatabase*, const gchar*): assertion 'pageURL' failed

Not sure if there anything can be done?

how to setup on Mac

There is no steps for mac.

Error: Cannot find module '/Users/i055023/node_modules/webkitgtk/lib/webkitgtk.node'

i get this errr...can you please help?

share gtk loop between instances

This idea cannot be done easily since each instance has a separate gtk_init() call.
To be investigated when/if we want to load pages from same domain as iframes.

Crash after `Name or service not known` error

When running two requests one after the other, If the first request contains a bad URL, the second request crashes the app.

The first request reports an error (as expected):

Error: Error resolving 'www.mezilla.org': Name or service not known
    at Error (native)
    at WebKit.<anonymous> (/home/gchudnov/Projects/node-webkitgtk/webkitgtk.js:609:27)
    at Timer.listOnTimeout (timers.js:89:15)

The second request terminates the app (unexpected):

iojs crashed with SIGSEGV in WebView::PngWrite()

Sample code (might be a bit long):

var WebKit = require('../');
var expect = require('expect.js');
var fs = require('fs');
var path  = require('path');

describe.only("Experiment", function suite() {
  this.timeout(10000);

  var w;

  before(function(cb) {
    var inst = new WebKit();
    var initOptions = {
      width: 1024,
      height: 768,
      depth: 32
    };

    inst.init(initOptions, function(err) {
      if(err) {
        cb(err);
      } else {
        w = inst;
        cb();
      }
    });
  });


  it("reports an error on Bad URL", function(done) {

    var href = "https://www.mezilla.org/en-US/";
    var filePath = path.resolve(__dirname, './shots/out1.png');

    function onRendered(err) {
      console.log('ON_RENDERED', err);
      console.log('DONE!');
      done();
    }

    w.once('idle', function() {
      w.png(filePath, onRendered);
    });

    var loadParams = {
    };

    w.load(href, loadParams, function(err) {
      if(err) {
        console.log('LOAD_ERROR', err);
        done(err);
      }
    });

  });

  it("should render Good URL after a bad one", function(done) {

    var href = "https://www.mozilla.org/en-US/";
    var filePath = path.resolve(__dirname, './shots/out2.png');

    function onRendered(err) {
      console.log('ON_RENDERED', err);
      console.log('DONE!');
      done();
    }

    w.once('idle', function() {
      w.png(filePath, onRendered);
    });

    var loadParams = {
    };

    w.load(href, loadParams, function(err) {
      if(err) {
        console.log('LOAD_ERROR', err);
        done(err);
      }
    });

  });

});

track long polling requests and do not count them for idling

If time(received-data) - time(sent-request) > timeout, then consider the request stalled and non-pertinent for load or idle events.
Wait for all other non-stalled requests to complete before considering ignoring stalled requests.
Two phases: load, idle.

No property named "allow-file-access-from-file-urls"

When trying to enable local file access you get this error:

(node:25711): GLib-GObject-WARNING **: g_object_set_valist: object class 'WebKitSettings' has no property named 'allow-file-access-from-file-urls'

I was browsing the webkitgtk documentation, and that seems to state the option is now "enable-file-access-from-file-uris"

Build Error on Ubuntu Vivid (15.04)

This was gone and appears to be back. Node-gyp isn't being very co-operative... perhaps

make: *** No rule to make target 'Release/lib.target/webextension.so', needed by 'lib/webextension'.  Stop.

support iojs v3 and the upcoming node.js v4

It looks it is needed to update the NAN library and the code that uses it.

I made the initial transformation.

The code compiles but there is at least one double free or corruption error.
I may have missed something, didn't have time to debug the problem yet. :(

cookies are not bound to web views

It is currently possible to set cookies, but setting two cookies of the same name on two separate webviews in the same application will fail: there is actually only one session.

Installation problem on Debian Jessie

When installing the module on Debian Jessie, there is a building issue,
Here is the log:

root@fc62df7ab5e3:/home# npm install webkitgtk
\
> [email protected] install /home/node_modules/webkitgtk
> node-gyp rebuild

make: Entering directory '/home/node_modules/webkitgtk/build'
  ACTION binding_gyp_mkdirs_target_make_dirs lib/ext
  TOUCH Release/obj.target/mkdirs.stamp
  CXX(target) Release/obj.target/webkitgtk/src/utils.o
../src/utils.cc: In function 'gchar* getStr(v8::Handle<v8::Object>, const gchar*)':
../src/utils.cc:11:32: warning: 'int NanUtf8String::Size() const' is deprecated (declared at ../node_modules/nan/nan.h:1759) [-Wdeprecated-declarations]
   if (str != NULL && str->Size() > 1) {
                                ^
  CXX(target) Release/obj.target/webkitgtk/src/gvariantproxy.o
  CXX(target) Release/obj.target/webkitgtk/src/webauthrequest.o
  CXX(target) Release/obj.target/webkitgtk/src/webresponse.o
  CXX(target) Release/obj.target/webkitgtk/src/webview.o
  SOLINK_MODULE(target) Release/obj.target/webkitgtk.node
  SOLINK_MODULE(target) Release/obj.target/webkitgtk.node: Finished
  COPY Release/webkitgtk.node
  CXX(target) Release/obj.target/webextension/src/utils.o
../src/utils.cc: In function 'gchar* getStr(v8::Handle<v8::Object>, const gchar*)':
../src/utils.cc:11:32: warning: 'int NanUtf8String::Size() const' is deprecated (declared at ../node_modules/nan/nan.h:1759) [-Wdeprecated-declarations]
   if (str != NULL && str->Size() > 1) {
                                ^
  CXX(target) Release/obj.target/webextension/src/webextension.o
  SOLINK(target) Release/obj.target/webextension.so
  SOLINK(target) Release/obj.target/webextension.so: Finished
  COPY Release/webextension.so
  ACTION binding_gyp_action_after_build_target_move_node lib/webkitgtk
make: *** No rule to make target 'Release/lib.target/webextension.so', needed by 'lib/webextension'.  Stop.
make: Leaving directory '/home/node_modules/webkitgtk/build'
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23)
gyp ERR! stack     at ChildProcess.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:810:12)
gyp ERR! System Linux 3.13.0-40-generic
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/node_modules/webkitgtk
gyp ERR! node -v v0.10.33
gyp ERR! node-gyp -v v1.0.1
gyp ERR! not ok 

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the webkitgtk package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls webkitgtk
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 3.13.0-40-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "webkitgtk"
npm ERR! cwd /home
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
npm ERR! not ok code 0

The problem is here:

make: *** No rule to make target 'Release/lib.target/webextension.so', needed by 'lib/webextension'.  Stop.

And it looks the directory named obj.target instead of lib.target

root@fc62df7ab5e3:/home/node-webkitgtk/build/Release# ls -la
total 136
drwxr-xr-x 4 root root  4096 Dec  2 13:59 .
drwxr-xr-x 4 root root  4096 Dec  2 13:59 ..
drwxr-xr-x 4 root root  4096 Dec  2 13:59 .deps
-rw-r--r-- 1 root root     0 Dec  2 13:59 linker.lock
drwxr-xr-x 4 root root  4096 Dec  2 13:59 obj.target
-rwxr-xr-x 1 root root 19368 Dec  2 13:59 webextension.so
-rwxr-xr-x 1 root root 99160 Dec  2 13:59 webkitgtk.node

Guess,

 '<@(PRODUCT_DIR)/lib.target/webextension.so'

and

'action': ['cp', '<@(PRODUCT_DIR)/lib.target/webextension.so', 'lib/ext/']

should be written without a dependency on lib.target name.
I'm not an expert on gyp and not sure what is the best way to do it.

get response data as stream

It would allow streaming responses right into nodejs.
webkitgtk <= 2.6.0 WebKitWebResource emits "received-data" events with data length but without any actual chunk.
This makes webkit_web_resource_get_data almost useless when dealing with huge files.

problems with the REPL

Currently, there is no ".scope" command actually asked by nodejs "repl" module.
As a consequence, the webkitgtk repl is currently more broken than usable...
See also
nodejs/node#3544

add a repl

Add a method .repl(opts) that takes nodejs repl options,
overwrites eval so it is eval'd in the context of the current webkitgtk window,
and runs javascript in the current window, as sync .run() scripts.

MediaSource and MediaStream flags

The MediaSource API allows the browser to use streams coming from JavaScript to play audio & video.

The MediaStream API allows recording video and audio.

They're currently disabled by default in webkit2gtk, but can be enabled with these options:

  • enable-mediasource
  • enable-media-stream

Thanks!

Custom Paper Sizes

Being able to feed in GTK paper size names is awesome, thank you. However we wondered what might involved in adding something even more flexible.

We'd love to contribute more directly but we don't speak c/c++, sorry. We're also unfamiliar with v8 / WebKitGTK. We figured we'd talk through how we thought this might work and try to help as much as we can.

I'm not sure how this would work on the c++ side but having that paper param be polymorphic would be pretty cool, perhaps...

Webkit(99).load('google.com').wait('idle').pdf({
  paper: { 
    width: 210, 
    height: 297, 
    unit: 'mm' 
  }
});

// Or

Webkit(99).load('google.com').wait('idle').pdf({
  paper: 'iso_a4'
});

... and here's some pseudo code which may / may not be of any help.

GtkPageSetup* setup = gtk_page_setup_new();
  Local<Object> paper = opts.paper->ToObject();
  if (paper.width == NULL) { 
    paper = gtk_paper_size_get_default();
    GtkPaperSize* paperSize = gtk_paper_size_new(paper);
  } else {
    const gchar custom_paper_name = 'some_placeholder_name';
    const gchar custom_paper_display_name = 'again_some_placeholder_name';
    const gdouble width = NanUInt32OptionValue(paper, H("width"), 210);
    const gdouble height = NanUInt32OptionValue(paper, H("height"), 297);
    const gchar unitStr = getStr(paper, "unit"); // assign the correct GTK unit based on this string...
    const GtkUnit unit = //  ... here? GTK_UNIT_POINTS || GTK_UNIT_MM || GTK_UNIT_INCH
    GtkPaperSize* paperSize = gtk_paper_size_new_custom(
      custom_paper_name,
      custom_paper_display_name,
      width,
      height,
      unit
    );   
  }

  gtk_page_setup_set_paper_size_and_default_margins(setup, paperSize);
  if (NanBooleanOptionValue(opts, H("fullpage"), false)) {
    gtk_page_setup_set_right_margin(setup, 0, GTK_UNIT_POINTS);
    gtk_page_setup_set_left_margin(setup, 0, GTK_UNIT_POINTS);
    gtk_page_setup_set_top_margin(setup, 0, GTK_UNIT_POINTS);
    gtk_page_setup_set_bottom_margin(setup, 0, GTK_UNIT_POINTS);
  }
  webkit_print_operation_set_page_setup(op, setup);

I really hope that's helpful. Thanks.

cancel 302 redirect

is it possible to cancel/stop a 302 redirect?

if not possible, i wonder if cause not "binded" in node-webkitgtk or not implemented upstream?

for example if i load http://google.com i get redirected to http://google.de and node-webkitgtk shows me the google search page. with what i tried:

var WebKit = require("webkitgtk");
WebKit.load("http://google.com", {
    offscreen: false,
    navigation: false
});

what i would like to see is what curl gets:

❱ curl -v google.com
* Rebuilt URL to: google.com/
*   Trying 173.194.112.9...
* Connected to google.com (173.194.112.9) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.1
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Location: http://www.google.de/?gfe_rd=cr&ei=ZFrHVtydGaWG8Qfu7bj4CA
< Content-Length: 258
< Date: Fri, 19 Feb 2016 18:09:40 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.de/?gfe_rd=cr&amp;ei=ZFrHVtydGaWG8Qfu7bj4CA">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

WebKitGTK process not being released

Hi @kapouer

I've been trying node-webkitgtk. After playing a while, I realised a costly memory consumption on my VM.

Digging around, I realised that the WebKitWebProcess never exits.

A quick example here:

var WebKit = require("webkitgtk");

WebKit('1024x768x16:99').load('http://google.com').pdf('google.pdf');
WebKit('1024x768x16:99').load('http://github.com').pdf('github.pdf');
WebKit('1024x768x16:99').load('http://news.com.au').pdf('news.pdf');

It runs smoothly to the end. After that, ps aux shows those process:

/usr/lib/x86_64-linux-gnu/webkit2gtk-4.0/WebKitWebProcess 26
/usr/lib/x86_64-linux-gnu/webkit2gtk-4.0/WebKitWebProcess 29
/usr/lib/x86_64-linux-gnu/webkit2gtk-4.0/WebKitWebProcess 16

They never gets released, therefore my memory consumption goes higher. It only disappear after quitting the node console.

Is there anything I missed on the webkit call that tells to release right after?

Really appreciate your help.

Cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.