adblocker_webview 2.3.0
adblocker_webview: ^2.3.0 copied to clipboard
A webview for flutter with adblocking capability. It's currently based on Official Flutter Webview Plugin.
AdBlocker WebView Flutter #
A Flutter WebView implementation that blocks ads and trackers using EasyList and AdGuard filter lists.
Features #
- π« Ad and tracker blocking using EasyList and AdGuard filters
- π Supports both URL and HTML content loading
- π Navigation control (back, forward, refresh)
- π± User agent strings for Android and iOS
- β‘ Early resource blocking for better performance
- π― Domain-based filtering and element hiding
- π Detailed logging of blocked resources
- π Custom JavaScript injection support
- β Whitelist/allowlist domains
- π Blocking statistics tracking
Getting Started #
Installation #
Add this to your pubspec.yaml:
dependencies:
adblocker_webview: ^2.2.0
Basic Usage #
import 'package:adblocker_webview/adblocker_webview.dart';
// Initialize the controller (preferably in main())
void main() async {
await AdBlockerWebviewController.instance.initialize(
FilterConfig(
filterTypes: [FilterType.easyList, FilterType.adGuard],
),
);
runApp(MyApp());
}
// Use in your widget
class MyWebView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AdBlockerWebview(
url: Uri.parse('https://example.com'),
shouldBlockAds: true,
adBlockerWebviewController: AdBlockerWebviewController.instance,
onLoadStart: (url) => print('Started loading: $url'),
onLoadFinished: (url) => print('Finished loading: $url'),
onLoadError: (url, code) => print('Error: $code'),
onProgress: (progress) => print('Progress: $progress%'),
);
}
}
Loading HTML Content #
AdBlockerWebview(
initialHtmlData: '<html><body>Hello World!</body></html>',
shouldBlockAds: true,
adBlockerWebviewController: AdBlockerWebviewController.instance,
)
Navigation Control #
final controller = AdBlockerWebviewController.instance;
// Check if can go back
if (await controller.canGoBack()) {
controller.goBack();
}
// Reload page
controller.reload();
// Execute JavaScript
controller.runScript('console.log("Hello from Flutter!")');
Whitelist/Blacklist Domains #
Disable ad blocking for specific trusted domains:
// Via configuration
await AdBlockerWebviewController.instance.initialize(
FilterConfig(
filterTypes: [FilterType.easyList],
allowedDomains: ['trusted-site.com', 'partner.com'],
blockedDomains: ['ads.example.com'],
),
);
// Dynamically at runtime
controller.addAllowedDomain('example.com');
controller.removeAllowedDomain('example.com');
// Check if a domain is whitelisted
if (controller.isAllowedDomain('https://example.com')) {
print('Ads allowed on this site');
}
Statistics Tracking #
Track blocked resources and CSS rules applied:
// Get statistics
final stats = controller.statistics;
print('Blocked: ${stats.blockedResourceCount} resources');
print('CSS rules applied: ${stats.cssRulesAppliedCount}');
print('Top blocked domains: ${stats.blockedDomains}');
// Reset statistics (e.g., when navigating to new page)
controller.resetStatistics();
Configuration #
The WebView can be configured with various options:
AdBlockerWebview(
url: Uri.parse('https://example.com'),
shouldBlockAds: true, // Enable/disable ad blocking
adBlockerWebviewController: AdBlockerWebviewController.instance,
onLoadStart: (url) {
// Page started loading
},
onLoadFinished: (url) {
// Page finished loading
},
onProgress: (progress) {
// Loading progress (0-100)
},
onLoadError: (url, code) {
// Handle loading errors
},
onUrlChanged: (url) {
// URL changed
},
);
Features in Detail #
Ad Blocking #
- EasyList and AdGuard filter list support
- Blocks resources before they load
- Hides ad elements using CSS rules
- Exception rules for whitelisting
Whitelist/Blacklist Support #
- Configure allowed domains via
FilterConfig - Configure blocked domains via
FilterConfig - Add/remove domains at runtime
- Subdomain matching (e.g.,
example.comallowssub.example.com)
Statistics #
- Track blocked resource count
- Track CSS rules applied
- Per-domain blocking statistics
- Reset statistics on demand
Resource Blocking #
- Blocks trackers and unwanted resources
- Early blocking for better performance
- Domain-based filtering
- Exception handling for allowed domains
Element Hiding #
- Hides ad containers and placeholders
- CSS-based element hiding
- Domain-specific rules
- Batch processing for performance
Migration Guide #
Migrating from 2.0.x to 2.2.x #
-
Controller Initialization
// Old (<= 2.2.0) await AdBlockerWebviewController.instance.initialize( FilterConfig( filterTypes: [FilterType.easyList, FilterType.adGuard], ), [] );// New (>= 2.2.0) await AdBlockerWebviewController.instance.initialize( FilterConfig( filterTypes: [FilterType.easyList, FilterType.adGuard], blockedDomains: ['ads.example.com'], ), );
Migrating from 1.2.0 to 2.0.0 #
Breaking Changes
-
Controller Initialization
// Old (1.2.0) final controller = AdBlockerWebviewController(); await controller.initialize(); // New (>= 2.0.0) await AdBlockerWebviewController.instance.initialize( FilterConfig( filterTypes: [FilterType.easyList, FilterType.adGuard], ), [] ); -
URL Parameter Type
// Old (1.2.0) AdBlockerWebview( url: "https://example.com", // ... ) // New (>= 2.0.0) AdBlockerWebview( url: Uri.parse("https://example.com"), // ... ) -
Filter Configuration
// Old (1.2.0) AdBlockerWebview( //.. other params additionalHostsToBlock: ['ads.example.com'], ); // New (>= 2.0.0) // Use FilterConfig for configuration await AdBlockerWebviewController.instance.initialize( FilterConfig( filterTypes: [FilterType.easyList, FilterType.adGuard], ), ); -
Event Handlers
// Old (1.2.0) onTitleChanged: (title) { ... } // New (>= 2.0.0) // Use onUrlChanged instead onUrlChanged: (url) { ... }
Deprecated Features
additionalHostsToBlockparameter is removed- Individual controller instances are replaced with singleton
onTitleChangedcallback is replaced withonUrlChanged
New Features
- Singleton controller pattern for better resource management
- Structured filter configuration using
FilterConfig - Improved type safety with
Urifor URLs - Enhanced filter list parsing and management
- Better performance through early resource blocking
Steps to Migrate
-
Update the package version in
pubspec.yaml:dependencies: adblocker_webview: ^2.2.0 -
Replace controller initialization with singleton pattern
-
Update URL parameters to use
Uriinstead ofString -
Replace deprecated callbacks with new ones
-
Update filter configuration to use
FilterConfig -
Test the application thoroughly after migration
Contributing #
We welcome contributions to improve the ad-blocking capabilities! Here's how you can help:
Getting Started #
- Fork the repository
- Create a new branch from
mainfor your feature/fix- Use
feature/prefix for new features - Use
fix/prefix for bug fixes - Use
docs/prefix for documentation changes
- Use
- Make your changes
- Write/update tests if needed
- Update documentation if needed
- Run tests and ensure they pass
- Submit a pull request
Before Submitting #
- Check that your code follows our style guide (see analysis badge)
- Write clear commit messages
- Include tests for new features
- Update documentation if needed
- Verify all tests pass
Pull Request Process #
- Create an issue first to discuss major changes
- Update the README.md if needed
- Update the CHANGELOG.md following semantic versioning
- The PR will be reviewed by maintainers
- Once approved, it will be merged
Code Style #
- Follow Effective Dart guidelines
- Use the provided analysis options
- Run
dart formatbefore committing
License #
This project is licensed under the BSD-3-Clause License - see the LICENSE file for details.