mirror of
https://github.com/microsoft/playwright-mcp.git
synced 2025-07-26 08:32:26 +08:00
chore(extension): convert to typescript (#603)
This commit is contained in:
parent
5df6c2431b
commit
ded00dc422
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@ -48,6 +48,8 @@ jobs:
|
|||||||
run: npx playwright install msedge
|
run: npx playwright install msedge
|
||||||
- name: Build
|
- name: Build
|
||||||
run: npm run build
|
run: npm run build
|
||||||
|
- name: Build Chrome extension
|
||||||
|
run: npm run build:extension
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
],
|
],
|
||||||
|
|
||||||
"background": {
|
"background": {
|
||||||
"service_worker": "background.js",
|
"service_worker": "lib/background.js",
|
||||||
"type": "module"
|
"type": "module"
|
||||||
},
|
},
|
||||||
|
|
||||||
|
@ -168,6 +168,6 @@
|
|||||||
<button id="connect-btn" class="button">Share This Tab</button>
|
<button id="connect-btn" class="button">Share This Tab</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="popup.js"></script>
|
<script src="lib/popup.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -14,24 +14,25 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Connection } from './connection.js';
|
import { Connection, debugLog } from './connection.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple Chrome Extension that pumps CDP messages between chrome.debugger and WebSocket
|
* Simple Chrome Extension that pumps CDP messages between chrome.debugger and WebSocket
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// @ts-check
|
type PopupMessage = {
|
||||||
|
type: 'getStatus' | 'connect' | 'disconnect';
|
||||||
|
tabId: number;
|
||||||
|
bridgeUrl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
function debugLog(...args) {
|
type SendResponse = (response: any) => void;
|
||||||
const enabled = true;
|
|
||||||
if (enabled) {
|
|
||||||
console.log('[Extension]', ...args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class TabShareExtension {
|
class TabShareExtension {
|
||||||
|
private activeConnections: Map<number, Connection>;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.activeConnections = new Map(); // tabId -> connection info
|
this.activeConnections = new Map(); // tabId -> connection
|
||||||
|
|
||||||
// Remove page action click handler since we now use popup
|
// Remove page action click handler since we now use popup
|
||||||
chrome.tabs.onRemoved.addListener(this.onTabRemoved.bind(this));
|
chrome.tabs.onRemoved.addListener(this.onTabRemoved.bind(this));
|
||||||
@ -42,27 +43,24 @@ class TabShareExtension {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle messages from popup
|
* Handle messages from popup
|
||||||
* @param {any} message
|
|
||||||
* @param {chrome.runtime.MessageSender} sender
|
|
||||||
* @param {Function} sendResponse
|
|
||||||
*/
|
*/
|
||||||
onMessage(message, sender, sendResponse) {
|
onMessage(message: PopupMessage, sender: chrome.runtime.MessageSender, sendResponse: SendResponse): boolean {
|
||||||
switch (message.type) {
|
switch (message.type) {
|
||||||
case 'getStatus':
|
case 'getStatus':
|
||||||
this.getStatus(message.tabId, sendResponse);
|
this.getStatus(message.tabId, sendResponse);
|
||||||
return true; // Will respond asynchronously
|
return true; // Will respond asynchronously
|
||||||
|
|
||||||
case 'connect':
|
case 'connect':
|
||||||
this.connectTab(message.tabId, message.bridgeUrl).then(
|
this.connectTab(message.tabId, message.bridgeUrl!).then(
|
||||||
() => sendResponse({ success: true }),
|
() => sendResponse({ success: true }),
|
||||||
(error) => sendResponse({ success: false, error: error.message })
|
(error: Error) => sendResponse({ success: false, error: error.message })
|
||||||
);
|
);
|
||||||
return true; // Will respond asynchronously
|
return true; // Will respond asynchronously
|
||||||
|
|
||||||
case 'disconnect':
|
case 'disconnect':
|
||||||
this.disconnectTab(message.tabId).then(
|
this.disconnectTab(message.tabId).then(
|
||||||
() => sendResponse({ success: true }),
|
() => sendResponse({ success: true }),
|
||||||
(error) => sendResponse({ success: false, error: error.message })
|
(error: Error) => sendResponse({ success: false, error: error.message })
|
||||||
);
|
);
|
||||||
return true; // Will respond asynchronously
|
return true; // Will respond asynchronously
|
||||||
}
|
}
|
||||||
@ -71,20 +69,17 @@ class TabShareExtension {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get connection status for popup
|
* Get connection status for popup
|
||||||
* @param {number} requestedTabId
|
|
||||||
* @param {Function} sendResponse
|
|
||||||
*/
|
*/
|
||||||
getStatus(requestedTabId, sendResponse) {
|
getStatus(requestedTabId: number, sendResponse: SendResponse): void {
|
||||||
const isConnected = this.activeConnections.size > 0;
|
const isConnected = this.activeConnections.size > 0;
|
||||||
let activeTabId = null;
|
let activeTabId: number | null = null;
|
||||||
let activeTabInfo = null;
|
|
||||||
|
|
||||||
if (isConnected) {
|
if (isConnected) {
|
||||||
const [tabId, connection] = this.activeConnections.entries().next().value;
|
const [tabId] = this.activeConnections.entries().next().value as [number, Connection];
|
||||||
activeTabId = tabId;
|
activeTabId = tabId;
|
||||||
|
|
||||||
// Get tab info
|
// Get tab info
|
||||||
chrome.tabs.get(tabId, (tab) => {
|
chrome.tabs.get(tabId, tab => {
|
||||||
if (chrome.runtime.lastError) {
|
if (chrome.runtime.lastError) {
|
||||||
sendResponse({
|
sendResponse({
|
||||||
isConnected: false,
|
isConnected: false,
|
||||||
@ -112,17 +107,15 @@ class TabShareExtension {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Connect a tab to the bridge server
|
* Connect a tab to the bridge server
|
||||||
* @param {number} tabId
|
|
||||||
* @param {string} bridgeUrl
|
|
||||||
*/
|
*/
|
||||||
async connectTab(tabId, bridgeUrl) {
|
async connectTab(tabId: number, bridgeUrl: string): Promise<void> {
|
||||||
try {
|
try {
|
||||||
debugLog(`Connecting tab ${tabId} to bridge at ${bridgeUrl}`);
|
debugLog(`Connecting tab ${tabId} to bridge at ${bridgeUrl}`);
|
||||||
// Connect to bridge server
|
// Connect to bridge server
|
||||||
const socket = new WebSocket(bridgeUrl);
|
const socket = new WebSocket(bridgeUrl);
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
socket.onopen = () => resolve(undefined);
|
socket.onopen = () => resolve();
|
||||||
socket.onerror = reject;
|
socket.onerror = () => reject(new Error('WebSocket error'));
|
||||||
setTimeout(() => reject(new Error('Connection timeout')), 5000);
|
setTimeout(() => reject(new Error('Connection timeout')), 5000);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -130,64 +123,64 @@ class TabShareExtension {
|
|||||||
// Store connection
|
// Store connection
|
||||||
this.activeConnections.set(tabId, info);
|
this.activeConnections.set(tabId, info);
|
||||||
|
|
||||||
this._updateUI(tabId, { text: '●', color: '#4CAF50', title: 'Disconnect from Playwright MCP' });
|
void this._updateUI(tabId, { text: '●', color: '#4CAF50', title: 'Disconnect from Playwright MCP' });
|
||||||
debugLog(`Tab ${tabId} connected successfully`);
|
debugLog(`Tab ${tabId} connected successfully`);
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
debugLog(`Failed to connect tab ${tabId}:`, error.message);
|
debugLog(`Failed to connect tab ${tabId}:`, error.message);
|
||||||
await this._cleanupConnection(tabId);
|
await this._cleanupConnection(tabId);
|
||||||
|
|
||||||
// Show error to user
|
// Show error to user
|
||||||
this._updateUI(tabId, { text: '!', color: '#F44336', title: `Connection failed: ${error.message}` });
|
void this._updateUI(tabId, { text: '!', color: '#F44336', title: `Connection failed: ${error.message}` });
|
||||||
|
|
||||||
throw error; // Re-throw for popup to handle
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_updateUI(tabId, { text, color, title }) {
|
private async _updateUI(tabId: number, { text, color, title }: { text: string; color: string | null; title: string }): Promise<void> {
|
||||||
chrome.action.setBadgeText({ tabId, text });
|
await chrome.action.setBadgeText({ tabId, text });
|
||||||
if (color)
|
if (color)
|
||||||
chrome.action.setBadgeBackgroundColor({ tabId, color });
|
await chrome.action.setBadgeBackgroundColor({ tabId, color });
|
||||||
chrome.action.setTitle({ tabId, title });
|
await chrome.action.setTitle({ tabId, title });
|
||||||
}
|
}
|
||||||
|
|
||||||
_createConnection(tabId, socket) {
|
private _createConnection(tabId: number, socket: WebSocket): Connection {
|
||||||
const connection = new Connection(tabId, socket);
|
const connection = new Connection(tabId, socket);
|
||||||
socket.onclose = () => {
|
socket.onclose = () => {
|
||||||
debugLog(`WebSocket closed for tab ${tabId}`);
|
debugLog(`WebSocket closed for tab ${tabId}`);
|
||||||
this.disconnectTab(tabId);
|
void this.disconnectTab(tabId);
|
||||||
};
|
};
|
||||||
socket.onerror = (error) => {
|
socket.onerror = error => {
|
||||||
debugLog(`WebSocket error for tab ${tabId}:`, error);
|
debugLog(`WebSocket error for tab ${tabId}:`, error);
|
||||||
this.disconnectTab(tabId);
|
void this.disconnectTab(tabId);
|
||||||
};
|
};
|
||||||
return { connection };
|
return connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disconnect a tab from the bridge
|
* Disconnect a tab from the bridge
|
||||||
* @param {number} tabId
|
|
||||||
*/
|
*/
|
||||||
async disconnectTab(tabId) {
|
async disconnectTab(tabId: number): Promise<void> {
|
||||||
await this._cleanupConnection(tabId);
|
await this._cleanupConnection(tabId);
|
||||||
this._updateUI(tabId, { text: '', color: null, title: 'Share tab with Playwright MCP' });
|
await this._updateUI(tabId, { text: '', color: null, title: 'Share tab with Playwright MCP' });
|
||||||
debugLog(`Tab ${tabId} disconnected`);
|
debugLog(`Tab ${tabId} disconnected`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clean up connection resources
|
* Clean up connection resources
|
||||||
* @param {number} tabId
|
|
||||||
*/
|
*/
|
||||||
async _cleanupConnection(tabId) {
|
async _cleanupConnection(tabId: number): Promise<void> {
|
||||||
const info = this.activeConnections.get(tabId);
|
const connection = this.activeConnections.get(tabId);
|
||||||
if (!info) return;
|
if (!connection)
|
||||||
|
return;
|
||||||
|
|
||||||
this.activeConnections.delete(tabId);
|
this.activeConnections.delete(tabId);
|
||||||
|
|
||||||
// Close WebSocket
|
// Close WebSocket
|
||||||
info.connection.close();
|
connection.close();
|
||||||
|
|
||||||
// Detach debugger
|
// Detach debugger
|
||||||
try {
|
try {
|
||||||
await info.connection.detachDebugger();
|
await connection.detachDebugger();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// Ignore detach errors - might already be detached
|
// Ignore detach errors - might already be detached
|
||||||
debugLog('Error while detaching debugger:', error);
|
debugLog('Error while detaching debugger:', error);
|
||||||
@ -196,9 +189,8 @@ class TabShareExtension {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Handle tab removal
|
* Handle tab removal
|
||||||
* @param {number} tabId
|
|
||||||
*/
|
*/
|
||||||
async onTabRemoved(tabId) {
|
async onTabRemoved(tabId: number): Promise<void> {
|
||||||
if (this.activeConnections.has(tabId))
|
if (this.activeConnections.has(tabId))
|
||||||
await this._cleanupConnection(tabId);
|
await this._cleanupConnection(tabId);
|
||||||
}
|
}
|
@ -14,22 +14,29 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// @ts-check
|
export function debugLog(...args: unknown[]): void {
|
||||||
|
|
||||||
function debugLog(...args) {
|
|
||||||
const enabled = true;
|
const enabled = true;
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
console.log('[Extension]', ...args);
|
console.log('[Extension]', ...args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type ProtocolCommand = {
|
||||||
|
id: number;
|
||||||
|
sessionId?: string;
|
||||||
|
method: string;
|
||||||
|
params?: any;
|
||||||
|
};
|
||||||
|
|
||||||
export class Connection {
|
export class Connection {
|
||||||
/**
|
private _debuggee: chrome.debugger.Debuggee;
|
||||||
* @param {number} tabId
|
private _rootSessionId: string;
|
||||||
* @param {WebSocket} ws
|
private _ws: WebSocket;
|
||||||
*/
|
private _eventListener: (source: chrome.debugger.DebuggerSession, method: string, params: any) => void;
|
||||||
constructor(tabId, ws) {
|
private _detachListener: (source: chrome.debugger.Debuggee, reason: string) => void;
|
||||||
/** @type {chrome.debugger.Debuggee} */
|
|
||||||
|
constructor(tabId: number, ws: WebSocket) {
|
||||||
this._debuggee = { tabId };
|
this._debuggee = { tabId };
|
||||||
this._rootSessionId = `pw-tab-${tabId}`;
|
this._rootSessionId = `pw-tab-${tabId}`;
|
||||||
this._ws = ws;
|
this._ws = ws;
|
||||||
@ -41,17 +48,17 @@ export class Connection {
|
|||||||
chrome.debugger.onDetach.addListener(this._detachListener);
|
chrome.debugger.onDetach.addListener(this._detachListener);
|
||||||
}
|
}
|
||||||
|
|
||||||
close(message) {
|
close(message?: string): void {
|
||||||
chrome.debugger.onEvent.removeListener(this._eventListener);
|
chrome.debugger.onEvent.removeListener(this._eventListener);
|
||||||
chrome.debugger.onDetach.removeListener(this._detachListener);
|
chrome.debugger.onDetach.removeListener(this._detachListener);
|
||||||
this._ws.close(1000, message || 'Connection closed');
|
this._ws.close(1000, message || 'Connection closed');
|
||||||
}
|
}
|
||||||
|
|
||||||
async detachDebugger() {
|
async detachDebugger(): Promise<void> {
|
||||||
await chrome.debugger.detach(this._debuggee);
|
await chrome.debugger.detach(this._debuggee);
|
||||||
}
|
}
|
||||||
|
|
||||||
_onDebuggerEvent(source, method, params) {
|
private _onDebuggerEvent(source: chrome.debugger.DebuggerSession, method: string, params: any): void {
|
||||||
if (source.tabId !== this._debuggee.tabId)
|
if (source.tabId !== this._debuggee.tabId)
|
||||||
return;
|
return;
|
||||||
// If the sessionId is not provided, use the root sessionId.
|
// If the sessionId is not provided, use the root sessionId.
|
||||||
@ -64,7 +71,7 @@ export class Connection {
|
|||||||
this._ws.send(JSON.stringify(event));
|
this._ws.send(JSON.stringify(event));
|
||||||
}
|
}
|
||||||
|
|
||||||
_onDebuggerDetach(source, reason) {
|
private _onDebuggerDetach(source: chrome.debugger.Debuggee, reason: string): void {
|
||||||
if (source.tabId !== this._debuggee.tabId)
|
if (source.tabId !== this._debuggee.tabId)
|
||||||
return;
|
return;
|
||||||
this._sendMessage({
|
this._sendMessage({
|
||||||
@ -76,19 +83,15 @@ export class Connection {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private _onMessage(event: MessageEvent): void {
|
||||||
* @param {MessageEvent} event
|
|
||||||
*/
|
|
||||||
_onMessage(event) {
|
|
||||||
this._onMessageAsync(event).catch(e => debugLog('Error handling message:', e));
|
this._onMessageAsync(event).catch(e => debugLog('Error handling message:', e));
|
||||||
}
|
}
|
||||||
|
|
||||||
async _onMessageAsync(event) {
|
private async _onMessageAsync(event: MessageEvent): Promise<void> {
|
||||||
/** @type {import('../src/cdpRelay').ProtocolCommand} */
|
let message: ProtocolCommand;
|
||||||
let message;
|
|
||||||
try {
|
try {
|
||||||
message = JSON.parse(event.data);
|
message = JSON.parse(event.data);
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
debugLog('Error parsing message:', error);
|
debugLog('Error parsing message:', error);
|
||||||
this._sendError(-32700, `Error parsing message: ${error.message}`);
|
this._sendError(-32700, `Error parsing message: ${error.message}`);
|
||||||
return;
|
return;
|
||||||
@ -97,7 +100,7 @@ export class Connection {
|
|||||||
debugLog('Received message:', message);
|
debugLog('Received message:', message);
|
||||||
|
|
||||||
const sessionId = message.sessionId;
|
const sessionId = message.sessionId;
|
||||||
const response = {
|
const response: { id: any; sessionId: any; result?: any; error?: { code: number; message: string } } = {
|
||||||
id: message.id,
|
id: message.id,
|
||||||
sessionId,
|
sessionId,
|
||||||
};
|
};
|
||||||
@ -106,7 +109,7 @@ export class Connection {
|
|||||||
response.result = await this._handleExtensionCommand(message);
|
response.result = await this._handleExtensionCommand(message);
|
||||||
else
|
else
|
||||||
response.result = await this._handleCDPCommand(message);
|
response.result = await this._handleCDPCommand(message);
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
debugLog('Error handling message:', error);
|
debugLog('Error handling message:', error);
|
||||||
response.error = {
|
response.error = {
|
||||||
code: -32000,
|
code: -32000,
|
||||||
@ -117,14 +120,14 @@ export class Connection {
|
|||||||
this._sendMessage(response);
|
this._sendMessage(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _handleExtensionCommand(message) {
|
private async _handleExtensionCommand(message: ProtocolCommand): Promise<any> {
|
||||||
if (message.method === 'PWExtension.attachToTab') {
|
if (message.method === 'PWExtension.attachToTab') {
|
||||||
debugLog('Attaching debugger to tab:', this._debuggee);
|
debugLog('Attaching debugger to tab:', this._debuggee);
|
||||||
await chrome.debugger.attach(this._debuggee, '1.3');
|
await chrome.debugger.attach(this._debuggee, '1.3');
|
||||||
const result = /** @type {any} */ (await chrome.debugger.sendCommand(this._debuggee, 'Target.getTargetInfo'));
|
const result: any = await chrome.debugger.sendCommand(this._debuggee, 'Target.getTargetInfo');
|
||||||
return {
|
return {
|
||||||
sessionId: this._rootSessionId,
|
sessionId: this._rootSessionId,
|
||||||
targetInfo: result.targetInfo,
|
targetInfo: result?.targetInfo,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (message.method === 'PWExtension.detachFromTab') {
|
if (message.method === 'PWExtension.detachFromTab') {
|
||||||
@ -134,36 +137,31 @@ export class Connection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async _handleCDPCommand(message) {
|
private async _handleCDPCommand(message: ProtocolCommand): Promise<any> {
|
||||||
const sessionId = message.sessionId;
|
const sessionId = message.sessionId;
|
||||||
/** @type {chrome.debugger.DebuggerSession} */
|
const debuggerSession: chrome.debugger.DebuggerSession = { ...this._debuggee };
|
||||||
const debuggerSession = { ...this._debuggee };
|
|
||||||
// Pass session id, unless it's the root session.
|
// Pass session id, unless it's the root session.
|
||||||
if (sessionId && sessionId !== this._rootSessionId)
|
if (sessionId && sessionId !== this._rootSessionId)
|
||||||
debuggerSession.sessionId = sessionId;
|
debuggerSession.sessionId = sessionId;
|
||||||
// Forward CDP command to chrome.debugger
|
// Forward CDP command to chrome.debugger
|
||||||
const result = await chrome.debugger.sendCommand(
|
const result = await chrome.debugger.sendCommand(
|
||||||
debuggerSession,
|
debuggerSession,
|
||||||
message.method,
|
message.method,
|
||||||
message.params
|
message.params
|
||||||
);
|
);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
_sendError(code, message) {
|
private _sendError(code: number, message: string): void {
|
||||||
this._sendMessage({
|
this._sendMessage({
|
||||||
error: {
|
error: {
|
||||||
// @ts-ignore
|
|
||||||
code,
|
code,
|
||||||
message
|
message,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private _sendMessage(message: object): void {
|
||||||
* @param {import('../src/cdpRelay').ProtocolResponse} message
|
|
||||||
*/
|
|
||||||
_sendMessage(message) {
|
|
||||||
this._ws.send(JSON.stringify(message));
|
this._ws.send(JSON.stringify(message));
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -14,24 +14,24 @@
|
|||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Popup script for Playwright MCP Bridge extension
|
|
||||||
*/
|
|
||||||
|
|
||||||
class PopupController {
|
class PopupController {
|
||||||
|
private currentTab: chrome.tabs.Tab | null;
|
||||||
|
private readonly bridgeUrlInput: HTMLInputElement;
|
||||||
|
private readonly connectBtn: HTMLButtonElement;
|
||||||
|
private readonly statusContainer: HTMLElement;
|
||||||
|
private readonly actionContainer: HTMLElement;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.currentTab = null;
|
this.currentTab = null;
|
||||||
this.bridgeUrlInput = /** @type {HTMLInputElement} */ (document.getElementById('bridge-url'));
|
this.bridgeUrlInput = document.getElementById('bridge-url') as HTMLInputElement;
|
||||||
this.connectBtn = /** @type {HTMLButtonElement} */ (document.getElementById('connect-btn'));
|
this.connectBtn = document.getElementById('connect-btn') as HTMLButtonElement;
|
||||||
this.statusContainer = /** @type {HTMLElement} */ (document.getElementById('status-container'));
|
this.statusContainer = document.getElementById('status-container') as HTMLElement;
|
||||||
this.actionContainer = /** @type {HTMLElement} */ (document.getElementById('action-container'));
|
this.actionContainer = document.getElementById('action-container') as HTMLElement;
|
||||||
|
|
||||||
this.init();
|
void this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
async init() {
|
async init(): Promise<void> {
|
||||||
// Get current tab
|
// Get current tab
|
||||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||||
this.currentTab = tab;
|
this.currentTab = tab;
|
||||||
@ -39,19 +39,24 @@ class PopupController {
|
|||||||
// Load saved bridge URL
|
// Load saved bridge URL
|
||||||
const result = await chrome.storage.sync.get(['bridgeUrl']);
|
const result = await chrome.storage.sync.get(['bridgeUrl']);
|
||||||
const savedUrl = result.bridgeUrl || 'ws://localhost:9223/extension';
|
const savedUrl = result.bridgeUrl || 'ws://localhost:9223/extension';
|
||||||
this.bridgeUrlInput.value = savedUrl;
|
if (this.bridgeUrlInput) {
|
||||||
this.bridgeUrlInput.disabled = false;
|
this.bridgeUrlInput.value = savedUrl;
|
||||||
|
this.bridgeUrlInput.disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
// Set up event listeners
|
// Set up event listeners
|
||||||
this.bridgeUrlInput.addEventListener('input', this.onUrlChange.bind(this));
|
if (this.bridgeUrlInput)
|
||||||
this.connectBtn.addEventListener('click', this.onConnectClick.bind(this));
|
this.bridgeUrlInput.addEventListener('input', this.onUrlChange.bind(this));
|
||||||
|
if (this.connectBtn)
|
||||||
|
this.connectBtn.addEventListener('click', this.onConnectClick.bind(this));
|
||||||
|
|
||||||
// Update UI based on current state
|
// Update UI based on current state
|
||||||
await this.updateUI();
|
await this.updateUI();
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateUI() {
|
async updateUI(): Promise<void> {
|
||||||
if (!this.currentTab?.id) return;
|
if (!this.currentTab?.id)
|
||||||
|
return;
|
||||||
|
|
||||||
// Get connection status from background script
|
// Get connection status from background script
|
||||||
const response = await chrome.runtime.sendMessage({
|
const response = await chrome.runtime.sendMessage({
|
||||||
@ -59,9 +64,15 @@ class PopupController {
|
|||||||
tabId: this.currentTab.id
|
tabId: this.currentTab.id
|
||||||
});
|
});
|
||||||
|
|
||||||
const { isConnected, activeTabId, activeTabInfo, error } = response;
|
const { isConnected, activeTabId, activeTabInfo, error } = response as {
|
||||||
|
isConnected: boolean;
|
||||||
|
activeTabId: number | undefined;
|
||||||
|
activeTabInfo?: { title?: string; url?: string };
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
if (!this.statusContainer || !this.actionContainer) return;
|
if (!this.statusContainer || !this.actionContainer)
|
||||||
|
return;
|
||||||
|
|
||||||
this.statusContainer.innerHTML = '';
|
this.statusContainer.innerHTML = '';
|
||||||
this.actionContainer.innerHTML = '';
|
this.actionContainer.innerHTML = '';
|
||||||
@ -84,21 +95,24 @@ class PopupController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
showStatus(type, message) {
|
showStatus(type: string, message: string): void {
|
||||||
|
if (!this.statusContainer)
|
||||||
|
return;
|
||||||
const statusDiv = document.createElement('div');
|
const statusDiv = document.createElement('div');
|
||||||
statusDiv.className = `status ${type}`;
|
statusDiv.className = `status ${type}`;
|
||||||
statusDiv.textContent = message;
|
statusDiv.textContent = message;
|
||||||
this.statusContainer.appendChild(statusDiv);
|
this.statusContainer.appendChild(statusDiv);
|
||||||
}
|
}
|
||||||
|
|
||||||
showConnectButton() {
|
showConnectButton(): void {
|
||||||
if (!this.actionContainer) return;
|
if (!this.actionContainer)
|
||||||
|
return;
|
||||||
|
|
||||||
this.actionContainer.innerHTML = `
|
this.actionContainer.innerHTML = `
|
||||||
<button id="connect-btn" class="button">Share This Tab</button>
|
<button id="connect-btn" class="button">Share This Tab</button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const connectBtn = /** @type {HTMLButtonElement} */ (document.getElementById('connect-btn'));
|
const connectBtn = document.getElementById('connect-btn') as HTMLButtonElement | null;
|
||||||
if (connectBtn) {
|
if (connectBtn) {
|
||||||
connectBtn.addEventListener('click', this.onConnectClick.bind(this));
|
connectBtn.addEventListener('click', this.onConnectClick.bind(this));
|
||||||
|
|
||||||
@ -108,21 +122,22 @@ class PopupController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
showDisconnectButton() {
|
showDisconnectButton(): void {
|
||||||
if (!this.actionContainer) return;
|
if (!this.actionContainer)
|
||||||
|
return;
|
||||||
|
|
||||||
this.actionContainer.innerHTML = `
|
this.actionContainer.innerHTML = `
|
||||||
<button id="disconnect-btn" class="button disconnect">Stop Sharing</button>
|
<button id="disconnect-btn" class="button disconnect">Stop Sharing</button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const disconnectBtn = /** @type {HTMLButtonElement} */ (document.getElementById('disconnect-btn'));
|
const disconnectBtn = document.getElementById('disconnect-btn') as HTMLButtonElement | null;
|
||||||
if (disconnectBtn) {
|
if (disconnectBtn)
|
||||||
disconnectBtn.addEventListener('click', this.onDisconnectClick.bind(this));
|
disconnectBtn.addEventListener('click', this.onDisconnectClick.bind(this));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
showActiveTabInfo(tabInfo) {
|
showActiveTabInfo(tabInfo?: { title?: string; url?: string }): void {
|
||||||
if (!tabInfo) return;
|
if (!tabInfo || !this.statusContainer)
|
||||||
|
return;
|
||||||
|
|
||||||
const tabDiv = document.createElement('div');
|
const tabDiv = document.createElement('div');
|
||||||
tabDiv.className = 'tab-info';
|
tabDiv.className = 'tab-info';
|
||||||
@ -133,36 +148,36 @@ class PopupController {
|
|||||||
this.statusContainer.appendChild(tabDiv);
|
this.statusContainer.appendChild(tabDiv);
|
||||||
}
|
}
|
||||||
|
|
||||||
showFocusButton(activeTabId) {
|
showFocusButton(activeTabId?: number): void {
|
||||||
if (!this.actionContainer) return;
|
if (!this.actionContainer)
|
||||||
|
return;
|
||||||
|
|
||||||
this.actionContainer.innerHTML = `
|
this.actionContainer.innerHTML = `
|
||||||
<button id="focus-btn" class="button focus-button">Switch to Shared Tab</button>
|
<button id="focus-btn" class="button focus-button">Switch to Shared Tab</button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const focusBtn = /** @type {HTMLButtonElement} */ (document.getElementById('focus-btn'));
|
const focusBtn = document.getElementById('focus-btn') as HTMLButtonElement | null;
|
||||||
if (focusBtn) {
|
if (focusBtn && activeTabId !== undefined)
|
||||||
focusBtn.addEventListener('click', () => this.onFocusClick(activeTabId));
|
focusBtn.addEventListener('click', () => this.onFocusClick(activeTabId));
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onUrlChange() {
|
onUrlChange(): void {
|
||||||
if (!this.bridgeUrlInput) return;
|
if (!this.bridgeUrlInput)
|
||||||
|
return;
|
||||||
|
|
||||||
const isValid = this.isValidWebSocketUrl(this.bridgeUrlInput.value);
|
const isValid = this.isValidWebSocketUrl(this.bridgeUrlInput.value);
|
||||||
const connectBtn = /** @type {HTMLButtonElement} */ (document.getElementById('connect-btn'));
|
const connectBtn = document.getElementById('connect-btn') as HTMLButtonElement | null;
|
||||||
if (connectBtn) {
|
if (connectBtn)
|
||||||
connectBtn.disabled = !isValid;
|
connectBtn.disabled = !isValid;
|
||||||
}
|
|
||||||
|
|
||||||
// Save URL to storage
|
// Save URL to storage
|
||||||
if (isValid) {
|
if (isValid)
|
||||||
chrome.storage.sync.set({ bridgeUrl: this.bridgeUrlInput.value });
|
void chrome.storage.sync.set({ bridgeUrl: this.bridgeUrlInput.value });
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async onConnectClick() {
|
async onConnectClick(): Promise<void> {
|
||||||
if (!this.bridgeUrlInput || !this.currentTab?.id) return;
|
if (!this.bridgeUrlInput || !this.currentTab?.id)
|
||||||
|
return;
|
||||||
|
|
||||||
const url = this.bridgeUrlInput.value.trim();
|
const url = this.bridgeUrlInput.value.trim();
|
||||||
if (!this.isValidWebSocketUrl(url)) {
|
if (!this.isValidWebSocketUrl(url)) {
|
||||||
@ -180,29 +195,28 @@ class PopupController {
|
|||||||
bridgeUrl: url
|
bridgeUrl: url
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.success) {
|
if (response.success)
|
||||||
await this.updateUI();
|
await this.updateUI();
|
||||||
} else {
|
else
|
||||||
this.showStatus('error', response.error || 'Failed to connect');
|
this.showStatus('error', response.error || 'Failed to connect');
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async onDisconnectClick() {
|
async onDisconnectClick(): Promise<void> {
|
||||||
if (!this.currentTab?.id) return;
|
if (!this.currentTab?.id)
|
||||||
|
return;
|
||||||
|
|
||||||
const response = await chrome.runtime.sendMessage({
|
const response = await chrome.runtime.sendMessage({
|
||||||
type: 'disconnect',
|
type: 'disconnect',
|
||||||
tabId: this.currentTab.id
|
tabId: this.currentTab.id
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.success) {
|
if (response.success)
|
||||||
await this.updateUI();
|
await this.updateUI();
|
||||||
} else {
|
else
|
||||||
this.showStatus('error', response.error || 'Failed to disconnect');
|
this.showStatus('error', response.error || 'Failed to disconnect');
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async onFocusClick(activeTabId) {
|
async onFocusClick(activeTabId: number): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await chrome.tabs.update(activeTabId, { active: true });
|
await chrome.tabs.update(activeTabId, { active: true });
|
||||||
window.close(); // Close popup after switching
|
window.close(); // Close popup after switching
|
||||||
@ -211,8 +225,9 @@ class PopupController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isValidWebSocketUrl(url) {
|
isValidWebSocketUrl(url: string): boolean {
|
||||||
if (!url) return false;
|
if (!url)
|
||||||
|
return false;
|
||||||
try {
|
try {
|
||||||
const parsed = new URL(url);
|
const parsed = new URL(url);
|
||||||
return parsed.protocol === 'ws:' || parsed.protocol === 'wss:';
|
return parsed.protocol === 'ws:' || parsed.protocol === 'wss:';
|
15
extension/tsconfig.json
Normal file
15
extension/tsconfig.json
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ESNext",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"strict": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"rootDir": "src",
|
||||||
|
"outDir": "./lib",
|
||||||
|
"resolveJsonModule": true
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src",
|
||||||
|
],
|
||||||
|
}
|
@ -17,9 +17,11 @@
|
|||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
|
"build:extension": "tsc --project extension",
|
||||||
"lint": "npm run update-readme && eslint . && tsc --noEmit",
|
"lint": "npm run update-readme && eslint . && tsc --noEmit",
|
||||||
"update-readme": "node utils/update-readme.js",
|
"update-readme": "node utils/update-readme.js",
|
||||||
"watch": "tsc --watch",
|
"watch": "tsc --watch",
|
||||||
|
"watch:extension": "tsc --watch --project extension",
|
||||||
"test": "playwright test",
|
"test": "playwright test",
|
||||||
"ctest": "playwright test --project=chrome",
|
"ctest": "playwright test --project=chrome",
|
||||||
"ftest": "playwright test --project=firefox",
|
"ftest": "playwright test --project=firefox",
|
||||||
|
Loading…
x
Reference in New Issue
Block a user