Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

detect if running as browser extension #267

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:theme_mode_handler/theme_mode_handler.dart';
import 'package:chrome_extension/runtime.dart';
import 'dart:js_interop';

import 'models/hive/app_options.dart';
import 'models/hive/pending_notifications.dart';
Expand All @@ -34,6 +36,7 @@ import 'tools/app_localizations.dart';
import 'tools/app_routes.dart';
import 'tools/app_themes.dart';
import 'tools/session_checker.dart';
import 'tools/browser_extension_detector.dart';
import 'widgets/spinning_peercoin_icon.dart';

late bool setupFinished;
Expand Down Expand Up @@ -178,6 +181,14 @@ void main() async {
);
}

if (kIsWeb && getChromeRuntimeId() != null) {
// Test:
print(getChromeRuntimeId());
chrome.runtime.onMessage.listen((e) {
e.sendResponse.callAsFunction(null, {'the_response': 1}.jsify());
});
}

//run
runApp(const PeercoinApp());
}
Expand Down
6 changes: 6 additions & 0 deletions lib/screens/wallet/wallet_home.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:peercoin/widgets/wallet/wallet_home/wallet_hide_bottom_sheet.dar
import 'package:peercoin/widgets/wallet/wallet_home/wallet_reset_bottom_sheet.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../tools/browser_extension_detector.dart';

import '../../models/available_coins.dart';
import '../../models/hive/coin_wallet.dart';
Expand Down Expand Up @@ -208,6 +209,11 @@ class _WalletHomeState extends State<WalletHomeScreen>
}
}

if (kIsWeb && isBrowserExtension()) {
// TODO move the listener here
print("Setting up Chrome message listener!");
}

checkPendingNotifications();
if (mounted) {
context.loaderOverlay.hide();
Expand Down
18 changes: 18 additions & 0 deletions lib/tools/browser_extension_detector.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'dart:js_interop';

@JS('chrome.runtime.id')
external JSString? get chromeRuntimeId;

String? getChromeRuntimeId() {
try {
final id = chromeRuntimeId;
return id?.toDart;
} catch (e) {
return null;
}
}

bool isBrowserExtension() {
// Wrapper around both Chrome and Firefox detection (TODO)
return getChromeRuntimeId() != null;
}
20 changes: 20 additions & 0 deletions web/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Message from website:', message);

// Check if the message type matches "PEERCOIN_BROWSER_EXTENSION"
if (message.type === "PEERCOIN_BROWSER_EXTENSION") {
// Forward the message to Flutter and handle the response
chrome.runtime.sendMessage(message, (response) => {
console.log('Response from Flutter:', response);

// Send the response back to the website
sendResponse(response);
});

// Indicate sendResponse will be handled asynchronously
return true;
}

// Ignore messages that do not match the type
return false;
});
31 changes: 31 additions & 0 deletions web/content_script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function injectPageScript() {
const script = document.createElement('script');
script.src = chrome.runtime.getURL('page_script.js');
script.onload = () => {
console.log('Peercoin extension page script injected successfully.');
script.remove(); // Optional: remove script after injection
};
(document.head || document.documentElement).appendChild(script);
}

// Inject the script when content script loads
injectPageScript();

// Listener for messages from the web page
window.addEventListener('message', (event) => {
// Validate the event source and ensure it's a Peercoin-specific message
if (event.source !== window || !event.data || event.data.type !== 'PEERCOIN_BROWSER_EXTENSION') return;

console.log('Content script received Peercoin extension event:', event.data);

// Relay the Peercoin event to the background script
chrome.runtime.sendMessage(event.data, (response) => {
if (chrome.runtime.lastError) {
console.error('Error sending Peercoin extension message to background:', chrome.runtime.lastError.message);
} else {
console.log('Received response from extension background script:', response);
}
});
});

console.log('Peercoin extension content script initialized.');
26 changes: 24 additions & 2 deletions web/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,21 @@
}
},
"permissions": [
"storage",
"activeTab"
"activeTab",
"scripting"
],
"host_permissions": [
"*://*.peercoin.net/*"
],
"web_accessible_resources": [
{
"resources": [
"page_script.js"
],
"matches": [
"<all_urls>"
]
},
{
"resources": [
"*.html",
Expand All @@ -42,5 +50,19 @@
"optional_permissions": [
"clipboardWrite",
"clipboardRead"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content_script.js"
],
"run_at": "document_start"
}
]
}
10 changes: 10 additions & 0 deletions web/page_script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
window.sendPeercoinExtensionMessage = function (message) {
const extensionMessage = {
type: '$PEERCOIN_BROWSER_EXTENSION',
payload: message,
timestamp: Date.now()
};
window.postMessage(extensionMessage, '*');
};

console.log('Peercoin extension page script loaded');
Loading