Browser-Use-mcp / features /monitoring.py
diamond-in's picture
Update features/monitoring.py
ace9c2b verified
"""
Network monitoring and performance analysis features
"""
import json
import time
import logging
from browser.driver import get_driver, cleanup_driver
logger = logging.getLogger(__name__)
def monitor_network_requests(url: str, duration: int = 5, use_persistent: bool = False) -> str:
"""Monitor network requests made by a page"""
driver = None
try:
driver = get_driver(None, use_persistent) # Don't navigate yet
# Inject JavaScript to monitor network
monitor_script = """
window.networkRequests = [];
const originalFetch = window.fetch;
const originalXHR = window.XMLHttpRequest.prototype.open;
// Monitor fetch requests
window.fetch = function(...args) {
const request = {
method: args[1]?.method || 'GET',
url: args[0],
timestamp: new Date().toISOString(),
type: 'fetch'
};
window.networkRequests.push(request);
return originalFetch.apply(this, args);
};
// Monitor XHR requests
window.XMLHttpRequest.prototype.open = function(method, url) {
const request = {
method: method,
url: url,
timestamp: new Date().toISOString(),
type: 'xhr'
};
window.networkRequests.push(request);
return originalXHR.apply(this, arguments);
};
"""
# Navigate to page and inject monitoring
driver.get(url)
driver.execute_script(monitor_script)
# Wait and collect requests
time.sleep(duration)
# Get collected requests
requests = driver.execute_script("return window.networkRequests;")
# Also get performance entries
performance_entries = driver.execute_script("""
return performance.getEntriesByType('resource').map(entry => ({
name: entry.name,
type: entry.initiatorType,
duration: entry.duration,
size: entry.transferSize,
startTime: entry.startTime
}));
""")
result = {
"intercepted_requests": requests,
"performance_entries": performance_entries,
"total_requests": len(requests) + len(performance_entries)
}
return json.dumps(result, indent=2, default=str)
except Exception as e:
logger.error(f"Error in monitor_network_requests: {e}")
return f"Error: {e}"
finally:
cleanup_driver(driver, use_persistent)
def get_console_logs(url: str, use_persistent: bool = False) -> str:
"""Capture browser console logs"""
driver = None
try:
driver = get_driver(None, use_persistent)
# Inject console log capture before navigation
driver.execute_script("""
window.consoleLogs = [];
const originalLog = console.log;
const originalError = console.error;
const originalWarn = console.warn;
console.log = function(...args) {
window.consoleLogs.push({
type: 'log',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalLog.apply(console, args);
};
console.error = function(...args) {
window.consoleLogs.push({
type: 'error',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalError.apply(console, args);
};
console.warn = function(...args) {
window.consoleLogs.push({
type: 'warn',
message: args.join(' '),
timestamp: new Date().toISOString()
});
originalWarn.apply(console, args);
};
""")
# Navigate to page
driver.get(url)
time.sleep(3) # Wait for logs
# Get captured logs
logs = driver.execute_script("return window.consoleLogs;")
return json.dumps(logs, indent=2, default=str)
except Exception as e:
logger.error(f"Error in get_console_logs: {e}")
return f"Error: {e}"
finally:
cleanup_driver(driver, use_persistent)