패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.3.0

universal_html

모든 플랫폼(포함 Flutter 및 서버 사이드)에서 작동하는 'dart:html'. 크로스플랫폼 개발과 HTML/XML 처리를 용이하게 합니다.

AndroidiOSmacOSWindowsLinux
30일 다운로드
66.2만
좋아요
516
Pub 점수
150

패키지 설치

flutter pub add universal_html

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

universal_html는 모바일, 데스크톱 및 서버 측 환경에서 Flutter를 포함한 모든 플랫폼에서 작동하는 통합된 'dart:html' API를 제공합니다. 실행 환경에 관계없이 일관된 HTML 및 XML 처리를 가능하게 하여 크로스플랫폼 개발을 간소화합니다. 이 패키지는 DOM 조작, HTTP 요청, 구조화된 콘텐츠 파싱을 위한 호환성 있는 인터페이스를 제공함으로써 웹과 비웹 환경 사이의 격차를 메웁니다. 웹과 백엔드 서비스 간에 공유 로직을 사용할 때 이상적이며, 코드 중복을 줄이고 개발 워크플로우를 단순화합니다.

사용 사례

  • 다중 플랫폼 웹 및 서버 로직
  • 공유 HTML/XML 구문 분석
  • 서버 측 렌더링 유틸리티
  • Flutter 앱에서 웹 컴포넌트 재사용
  • 일반적인 Dart 애플리케이션 빌드

주요 기능

  • 플랫폼에 관계없는 dart:html API
  • 모든 플랫폼에서 DOM 조작을 지원합니다
  • 내장된 XML/HTML 파싱
  • Flutter 및 서버와 원활하게 작동합니다
  • 경량이며 최소한의 종속성

적합한 대상

  • 다중 플랫폼을 대상으로 하는 개발자
  • HTML 처리가 필요한 백엔드 서비스
  • 웹 유사 기능을 필요로 하는 Flutter 앱
  • 웹과 서버 간의 코드 공유
  • 플랫폼별 조건을 피하는 프로젝트

고려 사항

  • 웹이 아닌 플랫폼에서 브라우저 고유 기능이 제한됨
  • 웹 외부의 일부 DOM 이벤트에 대한 지원 없음
  • 서버 측 실행 시 성능이 달라질 수 있습니다
  • 전체 브라우저 에뮬레이션을 위한 것이 아님
  • 비동기 작업을 신중하게 처리해야 합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Pub Package package publisher Github Actions CI

Introduction

A cross-platform replacement for dart:html (or package:web):

  • Eases cross-platform development
    • You can use this package in browsers, mobile, desktop, and server-side VM, and Node.JS.
    • Just replace dart:html / package:web imports with package:universal_html/universal_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.3.0

2. Use

import "package:universal_html/universal_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/universal_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', () {
    // ...
  });
}

카테고리

의존성

의존성 목록 9 개

소스 저장소

이 패키지를 사용하는 프로젝트