Giter VIP home page Giter VIP logo

universal_html's Introduction

Pub Package package publisher Github Actions CI

Introduction

A cross-platform dart:html:

  • Eases cross-platform development
    • You can use this package in browsers, mobile, desktop, and server-side VM, and Node.JS.
    • Just replace dart:html imports with package:universal_html/html.dart. Normal dart:html will continue to be used when application run in browsers.
  • Extensive support for processing HTML and XML documents
  • EventSource streaming support
    • Cross-platform dart:html EventSource ("application/event-stream").
    • If you want to customize EventSource HTTP headers outside browsers, see EventSourceOutsideBrowser.

The project is licensed under the Apache License 2.0. Some of the source code was adopted from the original dart:html in Dart SDK, which is documented in the relevant files.

Documentation

Similar projects

Getting started

1. Add dependency

In pubspec.yaml:

dependencies:
  universal_html: ^2.2.4

2. Use

import "package:universal_html/html.dart";

void main() {
  // Create a DOM tree
  final div = DivElement();
  div.append(Element.tag("h1")
    ..classes.add("greeting")
    ..appendText("Hello world!"));

  // Print outer HTML
  print(div.outerHtml);
  // --> <div><h1>Hello world</h1></div>

  // Do a CSS query
  print(div.querySelector("div > .greeting").text);
  // --> Hello world
}

Examples

Parsing HTML

Use parseHtmlDocument:

import 'package:universal_html/parsing.dart';

void main() {
  final htmlDocument = parseHtmlDocument('<html>...</html>');
}

Parsing XML

Use parseXmlDocument:

import 'package:universal_html/parsing.dart';

void main() {
  final xmlDocument = parseXmlDocument('<xml>...</xml>');
}

Scraping a website

Load a Window with WindowController:

import 'dart:io' show Cookie;
import 'package:universal_html/controller.dart';

Future main() async {
  // Load a document.
  final controller = WindowController();
  controller.defaultHttpClient.userAgent = 'My Hacker News client';
  await controller.openHttp(
    method: 'GET',
    uri: Uri.parse("https://news.ycombinator.com/"),
    onRequest: (HttpClientRequest request) {
      // Add custom headers
      request.headers.set('Authorization', 'headerValue');
      request.cookies.add(Cookie('cookieName', 'cookieValue'));
    },
    onResponse: (HttpClientResponse response) {
      print('Status code: ${response.statusCode}');
    },
  );

  // Select the top story using a CSS query
  final titleElements = controller.document.querySelectorAll(".athing > .title");
  final topStoryTitle = titleElements.first.text;

  // Print result
  print("Top Hacker News story is: $topStoryTitle");
}

EventSource

EventSource (see mozilla.org) is a browser API for reading "application/event-stream" streams. It has been supported by browsers for a long time.

import 'package:universal_html/html.dart';

Future<void> main() async {
  final eventSource = EventSource('http://example.com/events');
  await for (var message in event.onMessage) {
    print('Event type: ${message.type}');
    print('Event data: ${message.data}');
  }
}

EventSource requests from real browsers are typically authenticated using cookies. If you want to add cookies or customize other HTTP headers, you need to use EventSourceOutsideBrowser:

import 'package:universal_html/universal_html.dart';
import 'dart:io' show Cookie;

Future<void> main() async {
  final eventSource = EventSource('http://example.com/events');
  
  // The following block will NOT be executed in browsers.
  // Because compiler can infer instances of EventSourceOutsideBrowser are never constructed,
  // it will not appear in Javascript either.
  if (eventSource is EventSourceOutsideBrowser) {
    eventSource.onHttpClientRequest = (eventSource, request) {
      request.headers.set('Authorization', 'example');
      request.cookies.add(Cookie('name', 'value'));
    };
    eventSource.onHttpClientResponse = (eventSource, request, response) {
      // ...
    };
  }
  
  await for (var message in eventSource.onMessage) {
    print('Event:');
    print('  type: ${message.type}');
    print('  data: ${message.data}');
  }
}

Testing

import 'package:universal_html/controller.dart';
import 'package:test/test.dart';

void main() {
  setUp(() {
    WindowController.instance = WindowController();
  });
  
  test('test #1', () {
    // ...
  });
  
  test('test #2', () {
    // ...
  });
}

universal_html's People

Contributors

fsw avatar juancastillo0 avatar minhqdao avatar terrier989 avatar usamasarwar 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  avatar  avatar

universal_html's Issues

Quotes when 'backgroundColor' style

When I define a color value to the property backgroundColor, additionnal quotes are printed in outputed html.

final div = DivElement();
div.style.backgroundColor = "#FF8800";
print(div.outerHtml); // <div style="background-color: &quot;#FF8800&quot;"></div>

Build error: "Unable to find modules for some sources"

Hi all, I am getting the following error when importing this package for flutter web. Am I missing something or am I completely off-base?

bad import, a missing dependency in a package (or possibly a dev_dependency
needs to move to a real dependency), or a build failure (if importing a
generated file).

Please check the following imports:

import 'package:universal_html/html.dart';

I have the package under dependencies in pubspec.yaml:
universal_html: ^1.1.10 (it is not under dev_dependencies

I am on:
Flutter 1.13.8-pre.58 • channel master • https://github.com/flutter/flutter.git Framework • revision fabf4e3d0d (8 hours ago) • 2020-01-08 15:28:02 -0800 Engine • revision 46adf73d51 Tools • Dart 2.8.0 (build 2.8.0-dev.0.0 c0ca187f26)

WebRTC undefined getters on IOS and Android

I'm implementing WebRTC and what I have so far builds and runs as expected when I debug with Chrome but when I try to run my code on an Android or IOS emulator I get a few dozen of the following errors and the build fails.

lib/common/webRTC.dart:33:24: Error: Method not found: 'RtcPeerConnection'.
    myPeerConnection = RtcPeerConnection(rtcIceServers);

lib/screens/calling.dart:29:30: Error: The getter 'candidate' isn't defined for the class 'RtcPeerConnectionIceEvent'.
- 'RtcPeerConnectionIceEvent' is from 'package:universal_html/src/html_with_internals.dart' ('/usr/local/Caskroom/flutter/1.22.5/flutter/.pub-cache/hosted/pub.dartlang.org/universal_html-1.2.4/lib/src/html_with_internals.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'candidate'.

    'candidate': event.candidate.candidate,
                              
lib/screens/calling.dart:34:27: Error: The getter 'onTrack' isn't defined for the class 'RtcPeerConnection'.
- 'RtcPeerConnection' is from 'package:universal_html/src/html_with_internals.dart' ('/usr/local/Caskroom/flutter/1.22.5/flutter/.pub-cache/hosted/pub.dartlang.org/universal_html-1.2.4/lib/src/html_with_internals.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'onTrack'.
 
     peer.myPeerConnection.onTrack.listen((event) {
                                                    

I've tested a bunch of combinations but currently this is my environment:

Flutter (Channel master, 1.26.0-18.0.pre.90, on macOS 11.1 20C69 darwin-x64, locale en-US)
Platform android-30, build-tools 30.0.3
Xcode 12.4, Build version 12D4e
import 'package:universal_html/html.dart';

dependencies:
  flutter:
    sdk: flutter
  provider: ^4.3.2
  universal_html: ^1.2.4

and a snippet where I'm getting the errors:


peer.myPeerConnection.onIceCandidate.listen((event) {
      print('ice');
      if (event.candidate != null) {
        socket.send(jsonEncode({
          'type': 'candidate',
          'target': caller ?? contact,
          'candidate': event.candidate.candidate,
        }));
      }
    });

peer.myPeerConnection.onTrack.listen((event) {
      print('track');
    });

Any ideas on how to get it working on mobile?

Thanks!

`fileUri` property of ServerSideRenderer class not used

The document for the ServerSideRenderer suggests that I can specify a HTML file uri to use instead of the default one generated by that same class. Specifying that with the code below does not work:

void main() {
  final renderer = ServerSideRenderer(webAppMain, fileUri: 'web/index.html'); // <-- not working :(
  renderer.bind('localhost', 12345, onReady: (server) {});
}

Digging into the ServerSideRenderer class shows that the fileUri property is not used at all. It's just kept as a property in the class. Any workaround you can give in regards to the fileUri? Or am I missing anything here?

Not able to mock the package

I am using this library to use the html.window.open() method in my code, but I'm not able to mock it for my tests. I have imported the lib like this import "package:universal_html/html.dart" as html; in the code. My test tries to verify (using mockito) whether this method was called and also verify what argument was used.
Please help! Thanks :)

Running on Master Channel with SKIA breaks web browser

I have to run on Master Channel and run with:

flutter run --dart-define=FLUTTER_WEB_USE_SKIA=true -d chrome

When I do this w/ the web_browser/web_browser/example it displays the page but links and scrolling are broken.

I realize this might not be something you are interested in but I thought I'd ask just in case you know why.

Thanks for the package.

HtmlDriver does not run javascript

I was hoping that, as alluded to here, I could use an HtmlDriver to simulate a browser and fetch a page, running any scripts as a browser would do, and presenting me with the final rendered html.

Unfortunately, after a call to driver.setDocumentFromUri, driver.document.documentElement.outerHtml is just the html at the url I loaded, which includes script tags that were never run.

Is it possible to get HtmlDriver to run the javascript on loaded pages, and present me with the complete DOM, like I can do with JSDOM or Puppeteer in Node?

I tried using a ServerSideRenderer too, but I don't think that's right either. What am I supposed to specify for main? I just need it to evaluate any javascript built into the page, not my own main function.

How does the package work in all platforms ?

I am getting a compilation error when I try running the program on an android device. This is as expected as HTML is not supported on mobile devices. How can I use the package on non web platforms ?

Add possibility to get a node attribute

First of all, congrats to you! Your package is the only one that i've found that can handle with dumbs htmls inputs (broken ones).

Can you make the attributes of a Node being public? I mean, for now I'm using some regex approachs to got some attrs (like name/id/value).

// Current approach:
tree.getElementsByName('javax.faces.ViewState').first;
final jsfaces = Re.firstGroup(el.toString(), r'value=\s*"(.*)"');

// An interesting approach:
final jsfaces = tree.getElementsByName('javax.faces.ViewState').first.attributes['value'];

History is handled incorrectly

Execute this code:

print(html.window.location.pathname);

html.window.history.pushState("", "", "/a");
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.pushState("", "", "/b");
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.pushState("", "", "/c");
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.back();
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.back();
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.pushState("", "", "/d");
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

html.window.history.back();
await Future.delayed(Duration(milliseconds: 100));
print(html.window.location.pathname);

I get this output in a browser:

/
/a
/b
/c
/b
/a
/d

This is correct, since if one is located on /a´, goes to ´/d´ and then goes back, one would expect to end up back on /a`.

However, when executing the same code in flutter test, this output is received:

/
/a
/b
/c
/b
/a
/d
/c

It incorrectly sends one to /c instead of /a when going back from /d.
I have looked at the pushState implementation:

void pushState(dynamic data, String title, String url) {

I can see why this behavior is present. Shouldn't the function delete all elements after _index and then push the new state? That would comply with browser behavior.

QuerySelector on elements behaving like querySelectors on full document

Hi, I migrated to null-safety yesterday and in the process upgraded universal_html. I'm now encountering an issue when using querySelectors on elements (not the document). It seems like the querySelector is executed on almost the entire document instead of just the element and its children.

The regular html package produces the expected result.

import 'package:html/parser.dart';
import 'package:http/http.dart';
import 'package:universal_html/parsing.dart';
import 'package:universal_html/html.dart' as uhtml;

main() async {

	String html = (await get(Uri.parse("https://github.com/"))).body;

	print("html:");
	print(parse(html).querySelectorAll("a").length);
	print(parse(html).querySelector("nav").querySelectorAll("a").length);

	print("universal_html:");
	print(parseHtmlDocument(html).querySelectorAll("a").length);
	print(parseHtmlDocument(html).querySelector("nav").querySelectorAll("a").length);

	// workaround
	print(uhtml.Element.html(parseHtmlDocument(html).querySelector("nav").outerHtml).querySelectorAll("a").length);
}

Output:

html:
119
29
universal_html:
119
114
Removing disallowed element ...
29

Am I doing something wrong or is this an intended change? I'd rather not have to use the workaround as it seems like a performance issue. The other alternative would be changing my code to chain the selectors like "nav a" where html and universal_html provide the same result. (Not a 1:1 replacement though as there can be multiple nav elements)

Failed to execute "node" on "setAttribute": "[class]" is not a valid attribute name.

I have got error like this

Unhandled exception:
InvalidCharacterError: Failed to execute "node" on "setAttribute": "[class]" is not a valid attribute name.
#0      Element.setAttributeNS (package:universal_html/src/html/dom/element.dart:2123:7)
#1      Element.setAttribute (package:universal_html/src/html/dom/element.dart:2114:5)
#2      _HtmlParser._newNodeFrom.<anonymous closure> (package:universal_html/src/driver/dom_parser_driver.dart:239:20)
#3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
#4      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:235:25)
#5      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#6      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#7      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#8      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#9      _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#10     _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#11     _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#12     _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#13     _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23)
#14     _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:283:27)
#15     DomParserDriver.parseHtml (package:universal_html/src/driver/dom_parser_driver.dart:159:23)
#16     DomParserDriver.parseDocument (package:universal_html/src/driver/dom_parser_driver.dart:53:16)
#17     DomParserDriver.parseHtmlFromAnything (package:universal_html/src/driver/dom_parser_driver.dart:128:22)
#18     HtmlDriver.setDocumentFromContent (package:universal_html/src/driver/html_driver.dart:202:38)
#19     HtmlDriver.setDocumentFromUri (package:universal_html/src/driver/html_driver.dart:221:5)
<asynchronous suspension>
#20     CrawlerDictionary.getCambirdge (package:ielts_eccyl/src/utils/crawler_dictionary.dart:32:18)
#21     main (package:ielts_eccyl/main_test.dart:4:23)
#22     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#23     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

With my code

final driver = new HtmlDriver(userAgent: UserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'));
    var url = 'https://dictionary.cambridge.org/vi/dictionary/english-vietnamese/available';
    print(url);
    await driver.setDocumentFromUri(Uri.parse(url));
    final camEv =  driver.document.querySelectorAll('.english-vietnamese');

Layout Engine

Thank you very much for the library, it has helped me out a ton already.

Currently I'm trying to figure out the size of html elements, but if I understand the readme correctly this is not supported by this library, right? Do you know if dart:html has a BrowserImplementation that contains a LayoutEngine or where I could find one?

Thanks in advance, I appreciate the effort you've put into this library!

Missing tags after parse

Hey, for some reason some tags get lost when parsing them. Here's some code to reproduce the issue:

String html = "<td><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/about/\">about</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/\">summary</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/refs/\">refs</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/log/COPYING\">log</a><a class=\"active\" href=\"/pub/scm/linux/kernel/git/stable/linux.git/tree/COPYING\">tree</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/commit/COPYING\">commit</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/diff/COPYING\">diff</a><a href=\"/pub/scm/linux/kernel/git/stable/linux.git/stats/COPYING\">stats</a></td>";

Document d = DomParserDriver().parse(html, mime: "text/html");

d.documentElement.querySelectorAll("td").first; // throws an exception because the list is empty and the td element doesn't exist.

Am I doing something wrong? Thanks in advance for your help, I really like the library :)

namespace invalid argument

Not sure why I cant return the body of ebay's homepage.

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Invalid argument (namespace): "http://www.w3.org/1999/xlink" E/flutter (18121): #0 Element.setAttributeNS (package:universal_html/src/html/dom/element.dart:2128:7) E/flutter (18121): #1 _HtmlParser._newNodeFrom.<anonymous closure> (package:universal_html/src/driver/dom_parser_driver.dart:237:20) E/flutter (18121): #2 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8) E/flutter (18121): #3 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:235:25) E/flutter (18121): #4 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23) E/flutter (18121): #5 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23) E/flutter (18121): #6 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23) E/flutter (18121): #7 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23) E/flutter (18121): #8 _HtmlParser._newNodeFrom (package:universal_html/src/driver/dom_parser_driver.dart:248:23) E/flutter (18121): #9 _H I/flutter (18121): null I/flutter (18121):

while create url through html.Url.createObjectUrlFromBlob(blob); throw error

[ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: UnimplementedError
E/flutter (30797): #0 Url.createObjectUrlFromBlob (package:universal_html/src/html/api/history.dart:175:5)
E/flutter (30797): #1 _MyHomePageState.decryptFile (package:flutter_screenshot/main.dart:214:21)
E/flutter (30797):
E/flutter (30797): #2 _MyHomePageState.perfomEncryptionTasks (package:flutter_screenshot/main.dart:147:5)
E/flutter (30797):
E/flutter (30797):

i'm using this example

final blob = html.Blob([decryptedBytes]);
url = await html.Url.createObjectUrlFromBlob(blob);

Changes to conditional imports throw when building with DDC/dart2js

Changes introduced in build_modules: 4.0.2 prevent me from building with DDC and dart2js.
The changes in v4.0.2 prevent any conditional imports/exports for packages starting with dart:.

For more info, please see dart-lang/build#3173

A workaround/fix would be to introduce an indirection.

// new file: dart_js.dart
export 'dart:js';

// in js.dart
library universal_html.js;

export 'dart_js.dart'
    if (dart.library.io) 'src/js.dart'; // VM

This indirection should fix it but ... ehh, I wonder why this change was needed.

latest release Universal_html: ^ 2.0.8 not working Why?

There is no problem when I install the package .. But when I want to import it into the DART file, it does not work as if it was not installed and the red line appears under the import path.
I can only import the following path import 'package: universal_html / web_gl.dart';
The other paths cannot be imported.
what should I do ?

Error using getCurrentPosition for geolocation

I am trying to get the geolocation from the users browser for a Flutter web project but I am running into this error and cannot figure out why. I am able to use other methods of the library such as getting the users locales but geolocation fails. My guess is perhaps this is a permissions issue as I can get the users location if I use a similar JavaScript method in the Flutter index.html page and then can call the JS method directly using js.context.callMethod("geolocate"); from Flutter class.

import 'package:universal_html/prefer_universal/html.dart' as html;

if(html.window.navigator.geolocation != null) {
        html.window.navigator.geolocation.getCurrentPosition(enableHighAccuracy: false, timeout: Duration(microseconds: 10000))
            .then((position) {
              print("latitude ${position.coords}");
              print("longitude ${position.coords}");
            })
            .catchError((error){
              print("no gelolocation $error");
            });
      } else {
        print("no gelolocation ");
      }

The error output from the console is as follows:

longitude NoSuchMethodError: tried to call a non-function, such as null: 'html.window.navigator.geolocation[$getCurrentPosition]'

I can get languages to work

List<String> getLocales() => html.window.navigator.languages;
print("languages ${getLocales()}") ;

This outputs languages [en-US, en]

It seems that the library is working fine for other methods, it's just the geolocation that I cannot seem to get to work. Here is my flutter doctor output if that provides additional information:

[✓] Flutter (Channel master, v1.12.17-pre.44, on Mac OS X 10.15.1 19B88, locale en-US)
    • Flutter version 1.12.17-pre.44 at /Users/michaelritchie/Development/flutter
    • Framework revision f68cdacdd5 (19 hours ago), 2019-12-03 18:13:01 +0000
    • Engine revision faa11214c0
    • Dart version 2.7.0 (build 2.7.0-dev.2.1 e4344a568f)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/michaelritchie/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.2.1, Build version 11B53
    • CocoaPods version 1.8.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 41.1.2
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] VS Code (version 1.40.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.6.0

[✓] Connected device (3 available)
    • AOSP on IA Emulator • emulator-5554 • android-x86    • Android 9 (API 28) (emulator)
    • Chrome              • chrome        • web-javascript • Google Chrome 78.0.3904.108
    • Web Server          • web-server    • web-javascript • Flutter Tools

• No issues found!

Request microphone Permission Flutter Web

I need to use microphone in my flutter web application. i tried the bellow code but it only work if i request 'camera' .

import 'package:universal_html/html.dart' as html;


final perm = await html.window.navigator.permissions.query({"name": "camera"});
    if (perm.state == "denied") {
      Scaffold.of(context).showSnackBar(SnackBar(
        content: Text("Oops! Camera access denied!"),
        backgroundColor: Colors.orangeAccent,
      ));
      return;
    }
    final stream = await html.window.navigator.getUserMedia(video: true);

FileReader() crash when compiling to Android

I'm developing a multiplatform app, it works in Android, IOS and on the WEB. I have diferent services that I call depending of the platform, in one of this services I'm using FileReader() to upload a file from the web, it works when building for WEB. But if I don't comment the FileReader() object, to hide to compiler, it dont let me build the Android version, here is the output:

Launching lib/main.dart on Mi 9T in debug mode...
Running Gradle task 'assembleDebug'...
Unhandled exception:
Crash when compiling file:///Users/danielcardona/Flutter/ptf_online/ptf_online/lib/pages/datos_page/utils/filepicker_pc.dart,
at character offset 81:
RangeError (offset): Invalid value: Not in range 0..594, inclusive: 7359
#0      RangeError.checkValueInInterval (dart:core/errors.dart:283:7)
#1      Source.getLocation (package:kernel/ast.dart:7277:16)
#2      getLocation (package:front_end/src/fasta/messages.dart:16:52)
#3      ProcessedOptions.format (package:front_end/src/base/processed_options.dart:205:47)
#4      ProcessedOptions.report (package:front_end/src/base/processed_options.dart:228:29)
#5      CompilerContext.report (package:front_end/src/fasta/compiler_context.dart:69:13)
#6      Loader.addMessage (package:front_end/src/fasta/loader.dart:325:20)
#7      Loader.addProblem (package:front_end/src/fasta/loader.dart:287:12)
#8      LibraryBuilderImpl.addProblem (package:front_end/src/fasta/builder/library_builder.dart:284:19)
#9      SourceLibraryBuilder.addProblem (package:front_end/src/fasta/source/source_library_builder.dart:1250:47)
#10     BodyBuilder.addProblem (package:front_end/src/fasta/kernel/body_builder.dart:5611:20)
#11     BodyBuilder.addProblemErrorIfConst (package:front_end/src/fasta/kernel/body_builder.dart:5625:5)
#12     BodyBuilder.buildAbstractClassInstantiationError (package:front_end/src/fasta/kernel/body_builder.dart:5292:5)
#13     BodyBuilder.resolveRedirectingFactoryTargets (package:front_end/src/fasta/kernel/body_builder.dart:1125:13)
#14     BodyBuilder.finishFunction (package:front_end/src/fasta/kernel/body_builder.dart:983:5)
#15     DietListener.listenerFinishFunction (package:front_end/src/fasta/source/diet_listener.dart:908:14)
#16     DietListener.buildFunctionBody (package:front_end/src/fasta/source/diet_listener.dart:941:7)
#17     DietListener.endTopLevelMethod (package:front_end/src/fasta/source/diet_listener.dart:352:5)
#18     Parser.parseTopLevelMethod (package:_fe_analyzer_shared/src/parser/parser_impl.dart:2518:14)
#19     Parser.parseTopLevelMemberImpl (package:_fe_analyzer_shared/src/parser/parser_impl.dart:2372:14)
#20     Parser.parseTopLevelDeclarationImpl (package:_fe_analyzer_shared/src/parser/parser_impl.dart:495:14)
#21     Parser.parseUnit (package:_fe_analyzer_shared/src/parser/parser_impl.dart:352:15)
#22     SourceLoader.buildBody (package:front_end/src/fasta/source/source_loader.dart:329:14)
<asynchronous suspension>
#23     Loader.buildBodies (package:front_end/src/fasta/loader.dart:243:15)
<asynchronous suspension>
#24     KernelTarget.buildComponent.<anonymous closure> (package:front_end/src/fasta/kernel/kernel_target.dart:307:20)
#25     withCrashReporting (package:front_end/src/fasta/crash.dart:122:24)
#26     KernelTarget.buildComponent (package:front_end/src/fasta/kernel/kernel_target.dart:305:12)
#27     generateKernelInternal.<anonymous closure> (package:front_end/src/kernel_generator_impl.dart:149:38)
<asynchronous suspension>
#28     withCrashReporting (package:front_end/src/fasta/crash.dart:122:24)
#29     generateKernelInternal (package:front_end/src/kernel_generator_impl.dart:70:10)
#30     kernelForProgramInternal.<anonymous closure> (package:front_end/src/api_prototype/kernel_generator.dart:61:35)
#31     CompilerContext.runWithOptions.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:135:20)
<asynchronous suspension>
#32     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:123:46)
#33     new Future.sync (dart:async/future.dart:224:31)
#34     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:123:19)
#35     _rootRun (dart:async/zone.dart:1126:13)
#36     _CustomZone.run (dart:async/zone.dart:1023:19)
#37     _runZoned (dart:async/zone.dart:1518:10)
#38     runZoned (dart:async/zone.dart:1465:12)
#39     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:122:12)
#40     CompilerContext.runWithOptions (package:front_end/src/fasta/compiler_context.dart:133:10)
#41     kernelForProgramInternal (package:front_end/src/api_prototype/kernel_generator.dart:60:32)
#42     kernelForProgram (package:front_end/src/api_prototype/kernel_generator.dart:52:17)
#43     compileToKernel (package:vm/kernel_front_end.dart:320:41)
#44     FrontendCompiler.compile.<anonymous closure> (package:frontend_server/frontend_server.dart:446:54)
#45     new Future.<anonymous closure> (dart:async/future.dart:176:37)
#46     _rootRun (dart:async/zone.dart:1122:38)
#47     _CustomZone.run (dart:async/zone.dart:1023:19)
#48     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#49     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#50     _rootRun (dart:async/zone.dart:1126:13)
#51     _CustomZone.run (dart:async/zone.dart:1023:19)
#52     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#53     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
#54     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
#55     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
#56     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)


#0      DietListener.buildFunctionBody (package:front_end/src/fasta/source/diet_listener.dart:946:7)
#1      DietListener.endTopLevelMethod (package:front_end/src/fasta/source/diet_listener.dart:352:5)
#2      Parser.parseTopLevelMethod (package:_fe_analyzer_shared/src/parser/parser_impl.dart:2518:14)
#3      Parser.parseTopLevelMemberImpl (package:_fe_analyzer_shared/src/parser/parser_impl.dart:2372:14)
#4      Parser.parseTopLevelDeclarationImpl (package:_fe_analyzer_shared/src/parser/parser_impl.dart:495:14)
#5      Parser.parseUnit (package:_fe_analyzer_shared/src/parser/parser_impl.dart:352:15)
#6      SourceLoader.buildBody (package:front_end/src/fasta/source/source_loader.dart:329:14)
<asynchronous suspension>
#7      Loader.buildBodies (package:front_end/src/fasta/loader.dart:243:15)
<asynchronous suspension>
#8      KernelTarget.buildComponent.<anonymous closure> (package:front_end/src/fasta/kernel/kernel_target.dart:307:20)
#9      withCrashReporting (package:front_end/src/fasta/crash.dart:122:24)
#10     KernelTarget.buildComponent (package:front_end/src/fasta/kernel/kernel_target.dart:305:12)
#11     generateKernelInternal.<anonymous closure> (package:front_end/src/kernel_generator_impl.dart:149:38)
<asynchronous suspension>
#12     withCrashReporting (package:front_end/src/fasta/crash.dart:122:24)
#13     generateKernelInternal (package:front_end/src/kernel_generator_impl.dart:70:10)
#14     kernelForProgramInternal.<anonymous closure> (package:front_end/src/api_prototype/kernel_generator.dart:61:35)
#15     CompilerContext.runWithOptions.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:135:20)
<asynchronous suspension>
#16     CompilerContext.runInContext.<anonymous closure>.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:123:46)
#17     new Future.sync (dart:async/future.dart:224:31)
#18     CompilerContext.runInContext.<anonymous closure> (package:front_end/src/fasta/compiler_context.dart:123:19)
#19     _rootRun (dart:async/zone.dart:1126:13)
#20     _CustomZone.run (dart:async/zone.dart:1023:19)
#21     _runZoned (dart:async/zone.dart:1518:10)
#22     runZoned (dart:async/zone.dart:1465:12)
#23     CompilerContext.runInContext (package:front_end/src/fasta/compiler_context.dart:122:12)
#24     CompilerContext.runWithOptions (package:front_end/src/fasta/compiler_context.dart:133:10)
#25     kernelForProgramInternal (package:front_end/src/api_prototype/kernel_generator.dart:60:32)
#26     kernelForProgram (package:front_end/src/api_prototype/kernel_generator.dart:52:17)
#27     compileToKernel (package:vm/kernel_front_end.dart:320:41)
#28     FrontendCompiler.compile.<anonymous closure> (package:frontend_server/frontend_server.dart:446:54)
#29     new Future.<anonymous closure> (dart:async/future.dart:176:37)
#30     _rootRun (dart:async/zone.dart:1122:38)
#31     _CustomZone.run (dart:async/zone.dart:1023:19)
#32     _CustomZone.runGuarded (dart:async/zone.dart:925:7)
#33     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
#34     _rootRun (dart:async/zone.dart:1126:13)
#35     _CustomZone.run (dart:async/zone.dart:1023:19)
#36     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
#37     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
#38     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
#39     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
#40     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)

Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

* Where:
Script '/Users/danielcardona/developer/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 792

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command '/Users/danielcardona/developer/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s
Finished with error: Gradle task assembleDebug failed with exit code 1

The code I'm using to pick image for web:

import 'package:universal_html/prefer_sdk/html.dart' as html;

startFilePickerPc() {
  html.InputElement uploadInput = html.FileUploadInputElement();
  uploadInput.click();

  uploadInput.onChange.listen((e) {
    // read file content as dataURL
    final files = uploadInput.files;
    if (files.length == 1) {
      final file = files[0];

      final reader = new html.FileReader();
      reader.onLoadEnd.listen((e) {
        print(reader.result);
        //  _handleResult(reader.result);
      });

      reader.readAsDataUrl(file);
    }
  });
}

Any alternative to FileReader(), or any way to make it work, without needing to comment the web service, to compile for mobile device?

Thank so much for any help.

Usage of Worker class break unit tests

Hi,

I am currently using version 1.2.4 of universal_html.

I tried using the Worker class in order to execute a js script to upload a large file to an external server. It works fine in practice but it broke my unit test. I guess since the tests doesn't execute in the same environment as a web browser, the Worker class isn't defined. My tests can't compile and I get this kind of errors:

lib/screens/at_edit.dart:114:39: Error: The method 'Worker' isn't defined for the class 'ATEditScreen'.
 - 'ATEditScreen' is from 'package:at_front/screens/at_edit.dart' ('lib/screens/at_edit.dart').
Try correcting the name to the name of an existing method, or defining a method named 'Worker'.
                Worker uploadWorker = Worker('upload_worker.js');

Should I upgrade universal_html to 2.X (hence my flutter version which is still in a pre release version)?

Thanks

Different behaviours in universal_html & html

It seems like universal_html does not parse iframes like html. universal_html escapes the content of the iframes, while html doesn't.

Code to reproduce the issue:

import 'package:html/parser.dart';
import 'package:universal_html/parsing.dart';

main() async {

  String html = """ 
<!DOCTYPE HTML>
<html>
<head></head>
<body>
  <iframe>
  <!DOCTYPE html>
  <html>
  <head></head>
  <body>
    <p id="test-id">Test</p>
  </body>
  </html>
  </iframe>
</body>
</html>
  """;

  print(parseHtmlDocument(html).querySelector("iframe")!.innerHtml);
  print(parse(html).querySelector("iframe")!.innerHtml);
}

Output:

  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;&lt;/head&gt;
  &lt;body&gt;
    &lt;p id="test-id"&gt;Test&lt;/p&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  

  <!DOCTYPE html>
  <html>
  <head></head>
  <body>
    <p id="test-id">Test</p>
  </body>
  </html>

CharacterData.text throws on VM

Repro code:

      final node = Text('abc');
      node.text = 'hjkyu';

According to MDN, Node.text should

Returns / Sets the textual content of an element and all its descendants.

In case of those nodes that extend CharacterData, text could set the data directly, since a CharacterData Node is always a leaf node in the tree - there are no children.

Original exception I get:

  InvalidModificationError: Failed to execute "insertBefore" on "Node": This node type does not support this method.
  package:universal_html/src/html/dom/node.dart 372:5  Node.insertBefore
  package:universal_html/src/html/dom/node.dart 325:5  Node.append
  package:universal_html/src/html/dom/node.dart 279:5  Node.text=
  test/src/html/dom/node.dart 324:12                   _testNode.<fn>.<fn>

AssetNotFoundException in 1.1.16

I keep getting these when trying to compile with 1.1.16

In 1.1.15 works fine.

AssetNotFoundException: universal_html|lib/prefer_sdk/html.ddc.dill     
                                                                        
AssetNotFoundException: universal_html|lib/prefer_sdk/js.ddc.dill       
Error compiling dartdevc module:universal_html|lib/prefer_sdk/html.ddc.js

packages/universal_html/prefer_sdk/html.dart:15:1: Error: Error when reading 'packages/universal_html/src/_sdk/html.dart': File not found
export 'dart:html'
^


                                                                        
Error compiling dartdevc module:universal_html|lib/prefer_sdk/js.ddc.js 

packages/universal_html/prefer_sdk/js.dart:15:1: Error: Error when reading 'packages/universal_html/src/_sdk/js.dart': File not found
export 'dart:js'
^

I use the Flutter dev channel for compiling:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel dev, v1.15.3, on Mac OS X 10.15.2 19C57, locale en-NL)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Ultimate Edition (version 2017.1.6)
[✓] Connected device (2 available)

• No issues found!

Android and Integration Tests are unable to compile

Hi I use the js module. Web compiles fine without any errors but when it comes to Android and Integration tests (iOS) I get the following compiler error:

Using device iPhone 8.
236 Starting application: test_driver/app.dart
237 Compiler message:
238 ../../../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/universal_html-1.1.8/lib/src/js.dart:184:7: Error: Class 'JsObject with ListMixin<E>' inherits multiple members named '[]' with incompatible signatures.
239 Try adding a declaration of '[]' to 'JsObject with ListMixin<E>'.
240 class JsArray<E> extends JsObject with ListMixin<E> {
241       ^
242 ../../../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/universal_html-1.1.8/lib/src/js.dart:101:20: Context: This is the inherited member.
243   dynamic operator [](property) {
244                    ^^
245 org-dartlang-sdk:///third_party/dart/sdk/lib/core/list.dart:278:14: Context: This is the inherited member.
246   E operator [](int index);
247              ^^
248 ../../../../../Desktop/flutter/.pub-cache/hosted/pub.dartlang.org/universal_html-1.1.8/lib/src/js.dart:184:7: Error: The superclass, 'JsObject', has no unnamed constructor that takes no arguments.
249 class JsArray<E> extends JsObject with ListMixin<E> {
250       ^
251 Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
252 Failed to build bundle.

The imports used are:

import "package:universal_html/prefer_universal/js.dart";

and

import "package:universal_html/prefer_universal/html.dart"
    as html; 

Taken picture stretched only in iOS devices (Flutter web)

Hi. I'm using this this method and call it. when I take the image directly with the camera on portrait orientation the image get the size of the landscape orientation but it still portrait and stretched. The problem happens just with pictures taken with the iphone camera. picture from gallery are not stretched

The method

`pickImageWeb() async {

html.InputElement input = html.FileUploadInputElement();

input.type = 'file';
input.accept = 'image/*';

input.click();

input.addEventListener('change', (e) {
  // read file content as dataURL
  final files = input.files;
  if (files.length == 1) {
    final file = files[0];
    html.FileReader reader = html.FileReader();

    reader.onLoadEnd.listen((e) {
      setState(() {
        uploadedImage = reader.result;
      });
    });

    reader.onError.listen((fileEvent) {
      setState(() {
        var option1Text = "Some Error occured while reading the file";
      });
    });

    reader.readAsArrayBuffer(file);
  }
});
html.document.body.append(input); }`

Call :

floatingActionButton: FloatingActionButton( onPressed: () => pickImageWeb(), child: Icon( Icons.add, color: Colors.black, size: 35, ), ),

Displaying the picture :
Center( child: uploadedImage != null ? Image.memory( uploadedImage, fit: BoxFit.contain, ) : Text( 'Body of the scaffold', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 40, ), ), ),

Screenshots:
95429221_2831129003603062_670444931776512000_n
95663852_244409436675795_9097332983148314624_n

Databinding too ?

Thanks for this and universal IO library.

Does this provide a way to do databinding of JSON with HTML at runtime - loosely typed

I am not sure of the preferred databinding but mustache is a pretty well know runtime databinding language and there is a dart library for it :)

If you have other ideas I am all ears :)

Handle CustomEvents

Hey guys,

is it somehow possible to handle JS CustomEvents with your library?
I'm working on a web app using Flutter 1.9+ which is embedding a OpenLayers map using IFrameElement. I've added an event listener which is properly called when the CustomEvent is dispatched. My problem now is, that the listener takes in an object of the type Event but i need a CustomEvent to access detail data. I've already tried to cast the passed in object to CustomEvent which always fails.

Is there any chance to get this working?

html.document.removeEventListener is not running properly

No matter how I trigger the delete event, it's useless

void initState() {
  super.initState();
  html.document.addEventListener('visibilitychange', _webVisibilitychange);
}

void dispose() {
  super.dispose();
  html.document.removeEventListener('visibilitychange', _webVisibilitychange);
}

void _webVisibilitychange(html.Event event) {
  print(event);
  print(mounted);
}

Element.classes.add() not Unimplemented Exception

The example in "#3 Use" won't compile and throws an UnimplementedError

dependencies:
universal_html: ^1.2.1

Unhandled exception:
UnimplementedError

#0 _ElementCssClassSet.add (package:universal_html/src/html/dom/css_class_set.dart:435:5)
#1 main (file:///D:/codebase/dart/test1/cli/bin/cli.dart:27:21)
#2 _startIsolate. (dart:isolate-patch/isolate_patch.dart:299:32)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

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.