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

패키지 상세v0.6.0

chrome_extension

크롬 확장 프로그램에서 사용 가능한 `chrome.*` API에 접근하기 위한 라이브러리입니다.

Web
30일 다운로드
5.6천
좋아요
65
Pub 점수
160

패키지 설치

flutter pub add chrome_extension

패키지 개요

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

Flutter 웹 애플리케이션 내에서 `chrome.runtime`, `chrome.storage`, `chrome.tabs`와 같은 Chrome 확장 API에 접근할 수 있도록 해주는 Dart 라이브러리입니다. Flutter를 사용하여 Chrome 확장을 개발하는 개발자를 위해 특별히 설계되었으며, 브라우저 수준의 기능과 상호작용하기 위한 타입 안전한 인터페이스를 제공합니다. 이 패키지는 Flutter의 웹 기능과 네이티브 Chrome 확장 기능 사이의 격차를 메우며, 백그라운드 스크립트, 팝업 상호작용, 저장소 관리와 같은 확장 전용 동작을 원활하게 통합할 수 있게 해줍니다. xaha.dev에서 유지보수되며, 투명성과 커뮤니티 기여를 위해 GitHub에 호스팅되어 있습니다.

사용 사례

  • Flutter로 Chrome 확장 프로그램 만들기
  • 웹 앱에서 브라우저 스토리지에 액세스하는 방법
  • 탭 및 런타임 이벤트 관리
  • 팝업 인터페이스 만들기
  • 백그라운드 서비스 구현

주요 기능

  • chrome.* API에 대한 직접 접근
  • 타입 안전한 Dart 래퍼
  • 웹 전용 호환성
  • GitHub 호스팅 소스 코드
  • 간단한 pub add 통합

적합한 대상

  • Flutter 웹 개발자
  • 크롬 확장 프로그램 개발자
  • 브라우저 자동화 프로젝트
  • 크로스 플랫폼 확장 도구
  • Dart 중심 웹 앱 빌더

고려 사항

  • 웹 플랫폼에서만 작동합니다
  • Chrome 확장 매니페스트 설정이 필요합니다
  • Chrome 전용 기능에 한정
  • Chrome 브라우저가 아닌 경우 호환되지 않습니다
  • 자바스크립트 상호 운용성에 의존

원본 README

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

chrome_extension.dart

pub package Build Status

A library for accessing the chrome.* APIs available in Chrome extensions.

This allows to build Chrome extension with Dart & Flutter and to interop with the native APIs easily with a high-level type-safe interface.

The JS interop is build on top of dart:js_interop (static interop) which make it ready for future WASM compilation.

Buy Me A Coffee

Using the library

Example
chrome.tabs
import 'package:chrome_extension/tabs.dart';

void main() async {
  var tabs = await chrome.tabs.query(QueryInfo(
    active: true,
    currentWindow: true,
  ));
  print(tabs.first.title);
}
chrome.alarms
import 'package:chrome_extension/alarms.dart';

void main() async {
  await chrome.alarms.create('MyAlarm', AlarmCreateInfo(delayInMinutes: 2));

  var alarm = await chrome.alarms.get('MyAlarm');
  print(alarm!.name);
}
chrome.power
import 'package:chrome_extension/power.dart';

void main() {
  chrome.power.requestKeepAwake(Level.display);
}
chrome.runtime
import 'dart:js_interop';
import 'package:chrome_extension/runtime.dart';

void main() async {
  chrome.runtime.onInstalled.listen((e) {
    print('OnInstalled: ${e.reason}');
  });

  chrome.runtime.onMessage.listen((e) {
    e.sendResponse.callAsFunction(null, {'the_response': 1}.jsify());
  });
}
chrome.storage
import 'package:chrome_extension/storage.dart';

void main() async {
  await chrome.storage.local.set({'mykey': 'value'});
  var values = await chrome.storage.local.get(null /* all */);
  print(values['mykey']);
}
Available APIs

Documentation

Tips to build Chrome extensions with Flutter

Here are some personal tips to build Chrome extension using the Flutter UI framework.

Develop the app using Flutter Desktop

In order to develop in a comfortable environment with hot-reload, most of the app (the UI part) should be developed using Flutter desktop.

This requires an abstraction layer between the UI and the chrome_extension APIs.

In the Desktop entry point, a fake implementation of this abstraction layer is used, like this:

// lib/main_desktop.dart
void main() {
  // Inject a fake service that doesn't use the real chrome_extension package.
  var service = FakeBookmarkService();
  runApp(MyExtensionPopup(service));
}

abstract class BookmarkService {
  Future<List<Bookmark>> getBookmarks();
}

class FakeBookmarkService implements BookmarkService {
  @override
  Future<List<Bookmark>> getBookmarks() async => [Bookmark()];
}

Launch this entry point in desktop with
flutter run -t lib/main_desktop.dart -d macos|windows|linux

And the real entry point (the one used in the actual compiled extension) looks like:

// lib/main.dart
void main() {
  var service = ChromeBookmarkService();
  runApp(MyExtensionPopup(service));
}

class ChromeBookmarkService implements BookmarkService {
  @override
  Future<List<Bookmark>> getBookmarks() async {
    // Real implementation using chrome.bookmarks
    return (await chrome.bookmarks.getTree()).map(Bookmark.new).toList();
  }
}
Build script

web/manifest.json

{
  "manifest_version": 3,
  "name": "my_extension",
  "permissions": [
    "activeTab"
  ],
  "options_page": "options.html",
  "background": {
    "service_worker": "background.dart.js"
  },
  "action": {
    "default_popup": "index.html",
    "default_icon": {
      "16": "icons-16.png"
    }
  },
  "content_security_policy": {
    "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self';"
  }
}
// tool/build.dart
void main() async {
  await _process.runProcess([
    'flutter',
    'build',
    'web',
    '-t',
    'web/popup.dart',
    '--csp',
    '--web-renderer=canvaskit',
    '--no-web-resources-cdn',
  ]);
  for (var script in [
    'background.dart',
    'content_script.dart',
    'options.dart'
  ]) {
    await _process.runProcess([
      Platform.resolvedExecutable,
      'compile',
      'js',
      'web/$script',
      '--output',
      'build/web/$script.js',
    ]);
  }
}

It builds the flutter app and compiles all the other Dart scripts (for example: options.dart.js, popup.dart.js, background.dart.js)

Testing

Write tests for the extension using puppeteer-dart.

import 'package:collection/collection.dart';
import 'package:puppeteer/puppeteer.dart';

void main() async {
  // Compile the extension
  var extensionPath = '...';

  var browser = await puppeteer.launch(
    headless: false,
    args: [
      '--disable-extensions-except=$extensionPath',
      '--load-extension=$extensionPath',
      // Allow to connect to puppeteer from inside your extension if needed for the testing
      '--remote-allow-origins=*',
    ],
  );

  // Find the background page target
  var targetName = 'service_worker';
  var backgroundPageTarget =
      browser.targets.firstWhereOrNull((t) => t.type == targetName);
  backgroundPageTarget ??=
      await browser.waitForTarget((target) => target.type == targetName);
  var worker = (await backgroundPageTarget.worker)!;

  var url = Uri.parse(worker.url!);
  assert(url.scheme == 'chrome-extension');
  var extensionId = url.host;

  // Go to the popup page
  await (await browser.pages)
      .first
      .goto('chrome-extension://$extensionId/popup.html');

  // Etc...
}

카테고리

소스 저장소

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

아직 데이터가 없습니다.