Giter Site home page Giter Site logo

chrome.dart's Introduction

chrome.dart

Build Status

An library for accessing the Chrome APIs in a packaged app or extension.

Installing

Add this to your package's pubspec.yaml file:

dependencies:
  chrome: any

Using the library

import 'package:chrome/chrome_app.dart' as chrome;

void main() {
  chrome.runtime.getPlatformInfo().then((Map m) {
    print(m.toString());
  });
}

Also, see the FAQ.

In your pubspec.yaml

In order to build your app with pub build, you'll need to tell it to select the CSP compliant output of dart2js. To do that, add these lines:

transformers:
- chrome

to your pubspec.yaml file.

Documentation

Documentation is available at:

Breaking Changes

For version 0.5.0, we removed the older chrome.socket API in favor of the new chrome.sockets API. In order to continue using the older API, you can reference it directly via an import:

import 'package:chrome/gen/socket.dart';

chrome.dart's People

Contributors

adam-singer avatar adambender avatar aefalcon avatar alanrussian avatar amandacameron avatar bholtz avatar davidmorgan avatar devoncarew avatar drmarcii avatar eukreign avatar keertip avatar kevmoo avatar locks avatar seanburke-wf avatar seaneagan avatar srawlins avatar sunglim avatar wigahluk avatar

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

chrome.dart's Issues

Passing chrome.Entry to a Javascript function doesn't unwrap the DartObject

I'd expected a Dart chrome.Entry object to pass to JavaScript (as a function argument) with the equivalent Javascript type (chrome.fileSystem.Entry). Instead it appears as a DartObject. Passing the .jsProxy member sometimes seems to work but seems hacky/wrong.

For example: running this dart code

import 'package:chrome/chrome_app.dart' as chrome;
import 'package:js/js.dart' as js;

main() {
  var options = new chrome.ChooseEntryOptions(
      type: chrome.ChooseEntryType.OPEN_DIRECTORY);

  chrome.fileSystem.chooseEntry(options).then((result) {
    chrome.DirectoryEntry dirEntry = result.entry;
    js.context.saveHelloToDirectory(dirEntry);
  });
}

which passes a DirectoryEntry to this javascript

function saveHelloToDirectory(dirEntry) {
  console.log(dirEntry);

  dirEntry.getFile("hello_world.txt", {create: true, exclusive: false},

...

will give

Uncaught Error: NoSuchMethodError: Cannot call "getFile" on "#" (Object # has no method 'getFile')

If the dart line were changed to

js.context.saveHelloToDirectory(dirEntry.jsProxy);

then the code runs successfully but the compiler spits out

Warning: No member named 'jsProxy' in class 'DirectoryEntry'.

integrate `webview` wrapper

This one can be assigned to me, as I have an existing package to wrap the <webview> element in Dart:

http://pub.dartlang.org/packages/webview

I would happily deprecate that package and get it into here, where it most likely belongs :)

One possible roadblock at the moment is that it has an accompanying javascript file that it needs (lib/webview.js). Said javascript can be added explicitly to a user's html or automatically injected by the library (works very much like the js interop library in this regard). So any examples / tests that use the webview library need to copy the script or rely on the packages/ links, which don't work in Chrome on most OSes presently...

I thought I'd throw this in the backlog here to get comments, keep track of it. I could integrate it sooner (with the above caveat) or later (once the whole bartender / resource management solution lands in the Dart ecosystem).

cheers,

JSON: Add support for parsing "choices" in property parameters

Some parameters contain properties that have choices. Meaning they can be multiple object types or objects of multiple types.

Example of setIcon function from browser_action.json where imageData could be a $ref of ImageDataType or a javascript object with additional properties and $ref

{
        "name": "setIcon",
        "type": "function",
        "description": "Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the <b>path</b> or the <b>imageData</b> property must be specified.",
        "parameters": [
          {
            "name": "details",
            "type": "object",
            "properties": {
              "imageData": {
                "choices": [
                  { "\$ref": "ImageDataType" },
                  {
                    "type": "object",
                    "properties": {
                      "19": {"\$ref": "ImageDataType", "optional": true},
                      "38": {"\$ref": "ImageDataType", "optional": true}
                     }
                  }
                ],
                "optional": true,
                "description": "Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}'"
              },
              "path": {
                "choices": [
                  { "type": "string" },
                  {
                    "type": "object",
                    "properties": {
                      "19": {"type": "string", "optional": true},
                      "38": {"type": "string", "optional": true}
                    }
                  }
                ],
                "optional": true,
                "description": "Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals <code>scale</code>, then image with size <code>scale</code> * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}'"
              },
              "tabId": {
                "type": "integer",
                "optional": true,
                "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed."
              }
            }
          },
          {
            "type": "function",
            "name": "callback",
            "optional": true,
            "parameters": []
          }
        ]
      }

Other json idl also contain this structure.

bookmarks.json:            "choices": [
browser_action.json:                "choices": [
browser_action.json:                "choices": [
browser_action.json:                "choices": [
context_menus.json:            "choices": [
context_menus.json:            "choices": [
context_menus.json:          "choices": [
context_menus.json:                "choices": [
context_menus.json:            "choices": [
context_menus.json:                "choices": [
context_menus.json:            "choices": [
declarative_web_request.json:            "choices": [
declarative_web_request.json:            "choices": [
grep: devtools: Is a directory
events.json:              "choices": [
experimental_accessibility.json:            "choices": [
idltest.idl:    // we might be able to do is have a 'choices' list including all the
page_action.json:                "choices": [
page_action.json:                "choices": [
processes.json:            "choices": [
storage.json:                "choices": [
storage.json:                "choices": [
storage.json:                "choices": [
tabs.json:                 "choices": [
tabs.json:            "choices": [
tabs.json:                "choices": [
tabs.json:            "choices": [
test.json:            "choices": [
test.json:            "choices": [
test.json:            "choices": [
test.json:          {"choices": [ {"type": "string"}, {"type": "object", "isInstanceOf": "RegExp"} ], "name": "message", "optional": true}
windows.json:                "choices": [

Solution for handling this is still in discussion.

fix the drone.io tests

The tests are currently broken. I think because our drone.io scripts are using the old dart_analyzer instead of the new dartanalyzer tool.

test_windows.dart values not settable on 'create incognito window' test

I wonder about the following expects

              expect(window.left, 10);
              expect(window.top, 10);
              expect(window.width, 300);
              expect(window.height, 300);

I don't think its reliable cause other tests fail for the same reason. Any thoughts on what would cause those values not to set to the values passed? Feel free to close this out if you find it a non-issue. I'll put the github issue into the TODO comment.

Blob, File, TypedData, and more are transfered directly in VM but proxied in JS

Hi guys,

Contrary to the dart:js documentation, and owing to a bug, this is a big source of my current woes in interacting with the chrome fileSystem and I imagine you face the same issues. I found the bug (I think) and I posted it here:

https://code.google.com/p/dart/issues/detail?id=15053

If we could get that fixed we could directly use dart:html FileReaders, etc... without as many hoops (I've tested it and it works w/ my patch).

I'm posting an issue here to raise awareness, and in hopes that you may have some influence in fixing it. I hope that is okay.

thanks!

is the test app in test/app working?

Are people able to run the app in test/app? It doesn't seem like it should work as is, but I want to make sure that it wasn't changes of mine that regressed it.

library design question

Hi guys,

I have an architectural concern / question about the libraries, and I thought I should ask first before sending any pull request.

The current design, as far as I can tell, is aimed to provide a similar dot notation as the javascript APIs, so that one can make calls like this:

app.window.current().isMaximized();

To make this happen, there are singleton objects of type ChromeApp and ChromeWindow in this example (other libraries are doing similar).

The above does not feel as Darty to me, and there might also be some performance impact as compared to:

AppWindow.current.isMaximized

This is the alternative I propose. In this style, current becomes a static method on AppWindow, and isMaximized is a getter on the instance. This feels more like Dart to me, and the performance should be slightly better.

With import prefixes, the user would still have some leeway to prefix 1 name at the call site - that is their choice.

I'd also propose to change the library declarations from:

library chrome_app;

to:

library chrome.app.window;
library chrome.app.runtime;
etc...

I realize that this is a fairly subjective proposal. But I believe it actually will bring the APIs more in line with the javascript ones, in spite of the loss of the dot notation. Methods that are top-level in the javascript libraries can be top-level in the dart ones, without needing to live inside a class like ChromeFileSystem or ChromeRuntime. The user can still import those libraries as ChromeFileSystem or as ChromeRuntime if they want a prefix.

I've done quite a bit of work with AppWindow that I'd like to contribute, but it is currently written in the proposed style, so I thought it was a good idea to discuss this before sending any pull request. I'm open to refactoring it to the package's current style (ChromeApp, ChromeWindow, etc) but since the package is still young I'd like to hear pros / cons.

cheers,

js.scoped not declared

What steps will reproduce the problem?

  1. execute following code in chrome.dart serial example :
Serial.ports.then((result) {
logger.fine("getPorts = ${result}");
logger.fine("getPorts = ${result.runtimeType}");
result.forEach((port) {
  logger.fine("port = ${port} , ${port.runtimeType}");

  OptionElement optionElement = new OptionElement();
  optionElement.value = port;
  optionElement.text = port;
  selectElement.append(optionElement);
});

});
2.
3.

What is the expected output? What do you see instead?

Should be no error, but always "Breaking on exception: No top-level method 'js.scoped' declared."

What version of the product are you using? On what operating system?

Dart Editor version 1.0.0_r30798 (STABLE)
Dart SDK version 1.0.0.10_r30798

Please provide any additional information below.

I think js.scoped method has been removed from js package, I tried to add : import 'dart:js' as js;

however, still same failed result

Is there anyone knows how to bypass this issue ?

Implement chrome.runtime.getPlatformInfo

And then remove the dart:html dependency from common.dart, i.e. the following code:

bool isLinux() {
  return _platform().indexOf('linux') != -1;
}

bool isMac() {
  return _platform().indexOf('mac') != -1;
}

bool isWin() {
  return _platform().indexOf('win') != -1;
}

String _platform() {
  String str = window.navigator.platform;

  return (str != null) ? str.toLowerCase() : '';
}

hosting chrome extension APIs

Hey all, I need access to a few of the chrome extension APIs (separate from the chrome app APIs). https://developer.chrome.com/extensions/api_index.html

My question is, is this repo the best place to host an extension API library? Or should it be in a separate, parallel project? I.e., should it be referenced via:

package:chrome/chrome_ext.dart

or via

package:chrome_ext/chrome_ext.dart

There are many APIs that are shared between the two platforms, and it'd be great to reuse code where possible. My understanding though is that the same APIs (chrome.runtime, ...) may have slight differences or version skew between extensions and apps. I'm not 100% sure about this, but it would make code re-use tricky.

So, should the extension APIs be hosted in this project or a parellel project?

windows.dart does not get exported to chrome_app.dart

Not exactly sure why the mismatch is happening. It seems like when you call ChromeAppWindow.create the future object is a AppWindow which has a property AppWindow.contentWindow of type Window. That Window object does not have any Events to listen on. So the path that I find hard to figure out is if ChromeAppWindow.create is called how does one listen to events such as maximize, minimize, etc..

http://developer.chrome.com/apps/app_window.html#type-AppWindow

Maybe ChromeWindows should have a fromProxy constructor? This is where the original API seems to become confusing about returned javascript objects.

usb.dart defines Recipient._INTERFACE instead of Recipient.INTERFACE

I'm currently porting a subset of dfu-programmer functionality to Dart using this package to take advantage of Chrome's Packaged App USB API.

The following code:

var controlTransferInfo = new chrome.ControlTransferInfo(
    direction: chrome.Direction.IN,
    recipient: chrome.Recipient._INTERFACE,
    requestType: chrome.RequestType.CLASS,
    request: DFU_ABORT_REQUEST,
    value: 0,
    index: INTERFACE_NUMBER,
    length: 0,
    data: null);
chrome.usb.controlTransfer(deviceHandle, controlTransferInfo)

produces:

Uncaught Error: Instance of 'UnknownJavaScriptObject'
Error: Invalid value for argument 2. Property 'recipient': Value must be one of: [device, interface, endpoint, other].
    at validate (extensions::schemaUtils:34:13)
    at Object.normalizeArgumentsAndValidate (extensions::schemaUtils:117:3)
    at Object.<anonymous> (extensions::binding:307:30)
    ...

For the time being, I'm forced to use recipient: 'interface', but this no longer allows me to take advantage of Dart's checked mode.

I've traced this to usb.dart#L269, which is generated from usb.idl#L13. I suspect this may actually stem from a limitation or bug in the parsers package used to generate the gen/*.dart files.

drone.io

@financecoding, can you commit the script that's being run on drone.io to the repo (bin/drone_io.sh, tool/drone_io.sh, ...)? It'll let people adjust the drone.io build w/o needing to have access to that account. This would be in support of things like #72. Thanks!

Unit test style

Noticed we have two different ways unit tests are being implemented. One is wrapping main() into a class. The other is having main() as a top level function. Can we choose one and go forward with tests in that style?

  app.main();
  storage.main();

  new TestFileSystem().main();
  new TestI18N().main();
  new TestPower().main();
  new TestPushMessaging().main();
  new TestRuntime().main();
  new TestSerial().main();
  new TestSocket().main();

Update examples

Update and test javascript references in examples.

<script src="packages/browser/dart.js"></script>
<script src="packages/browser/interop.js"></script>
<script src="packages/js/dart_interop.js"></script>

Run dartdoc continuously on drone.io ?

Hi guys,

What do y'all think about running dartdoc on drone.io and having it publish to gh-pages? I do this for a few of my open source projects, and I think it would be quite useful here. Then we could add the gh-pages url to the pubspec, and there would be a direct link from Pub to the docs.

I don't have access to the drone account (and I don't really need / want it!) so here's a pointer to one of my project settings:

https://drone.io/github.com/rmsmith/tags/admin

Idea : maybe we can have a shell script checked into the repo and drone.io will just run that? then all repo collaborators could modify the drone script to try stuff like this?

cheers!
P.S if someone does want to try this, 2 things:

  1. you need to setup the drone project to filter branch triggers (master only probably), so that it won't run builds from gh-pages commits.
  2. you need to get the SSH-key from drone and add it to the github settings in order for drone to be able to push the commits to gh-pages.

test_app.dart test bugs

disabled a few of the failing tests on mac. Mostly related to fullscreen. I'll try to isolate if possible. Noticed that expect(win.bounds.top, equals(20)); never matches on mac for some reason. Close this out if its not really an issue.

identity_example throwing CSP error

Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

How to save to `chrome.storage` on close / exit?

Hi guys,

Sorry if this is a bad place to ask questions, but I don't think many people are doing Chrome + Dart yet so I thought I'd try here first.

Does anyone have success saving small amounts of data (like settings, etc...) to chrome.storage on close? I've tried both onClosed and runtime.onSuspend but I can't get it to work. I receive the onClosed event, because I use that to close other child windows so I know the event is received in the Dart code. But if I try to save to storage from that event handler it does not work.

The thing is that if I use onClosed in javascript ( from my background / event script) then I can save to storage :/ So it seems that the js-interop is somehow preventing me a chance to persist..... a timing thing I suppose.

Any ideas?

thanks!

Sidebar in devtools seems not to work

in devtools_background.dart

chrome.devtools.panels.elements.createSidebarPane('Sidebar').then(sidebarCreated)

void sidebarCreated(chrome.ExtensionSidebarPane newSidebar) {
  sidebar = newSidebar;
  sidebar
      ..setHeight('100px')
      ..setObject('["test": "value"]', 'rootTitle');
}

has no recognizable effect.

expose the syncFileSystem API

I have a mostly working copy that I need to make a few tweaks to. It returns and uses js.Proxy, and defines convenience wrappers around those proxies (chrome.FileSystem).

I think once it's committed, we should look at rationalizing our use of the various file system calls (runtime, fileSystem, syncFileSystem, media gallery), and probably move to making the convenience wrappers the things that are actually returned, instead of the proxies.

Project clean up

  • Remove all *.dart.js.dep/.dart.js.map/*.dart.js
  • Add build tasks for all examples in hop_runner.dart
  • Remove all compile.sh scripts

test_storage.dart fails on chrome.storage.local.set_get

14
ERROR
chrome.storage.local.set_get. Test failed: Caught The null object does not have a method '[]'. NoSuchMethodError : method not found: '[]' Receiver: null Arguments: ["foo"]
dart:core                                                                                                                    Object.noSuchMethod
chrome-extension://dkcoaocmommednefibaopcmobfekilmn/src/test_storage.dart 31:26                                              main.<fn>.<fn>.<fn>
dart:async                                                                                                                   _createTimer.<fn>
file:///Volumes/data/b/build/slave/dartium-mac-full-trunk/build/src/dart/tools/dom/src/native_DOMImplementation.dart 255:17  _Timer._Timer.<fn>

library versioning

What are people's thoughts re: the versioning of the chrome library? Currently it's at v 0.0.1. I think we want to bump that up a bit higher. Two ideas are:

-approx. track the SDK version. it's what many pub libraries (at least the ones from the svn repo) do
-track the chrome api version. Currently I believe this is as 27. So we might do something like use version 27.0.0, and bump up the version as we make changes (27.0.1, 27.1.0, ...), up until we add an API that relies on chrome 28.

Thoughts?

@financecoding @kevmoo

Library name conflicts with dart:chrome

Should we change the chrome library to chrome_app. This would mirror chrome_ext, making it clear why the two exist, plus would prevent the name conflict with dart:chrome.

port.onMessage.addListener seems not to work

I tried to build a devtools extension

The content script message.js

var port = chrome.runtime.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});

background.dart

library ext_example;

import 'dart:html' as dom;
import 'package:chrome/chrome_ext.dart' as chrome;

void main() {
  chrome.runtime.onConnect.listen((chrome.Port port) {
    port.onMessage.addListener().then(processMessage);
}

void processMessage(e) {
  dom.window.console.log('=== message received ===');
}

Exception when the content script calls port.postMessage()

Error in event handler for (unknown): undefined extensions::event_bindings:375
Event.dispatch_ extensions::event_bindings:375
Event.dispatch extensions::event_bindings:392
dispatchOnMessage extensions::messaging:307

I wondered also why the message name is addListener (which returns a Future) instead of listen (and returns a Stream).

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.