-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
71 lines (59 loc) · 2.32 KB
/
background.js
File metadata and controls
71 lines (59 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.command === 'startListening') {
startListening();
}
});
function startListening() {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTab = tabs[0];
if (activeTab.url.startsWith('chrome://')) {
console.warn('Cannot run voice recognition on chrome:// URLs');
return;
}
chrome.scripting.executeScript({
target: { tabId: activeTab.id },
function: initiateVoiceRecognition
});
});
}
function initiateVoiceRecognition() {
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
recognition.start();
recognition.onresult = (event) => {
const speechResult = event.results[0][0].transcript.toLowerCase();
console.log('Speech received: ' + speechResult);
if (speechResult === 'change next' || speechResult === 'next tab') {
chrome.runtime.sendMessage({ command: 'changeTab', direction: 'next' });
} else if (speechResult === 'change back' || speechResult === 'previous tab') {
chrome.runtime.sendMessage({ command: 'changeTab', direction: 'previous' });
}
};
recognition.onspeechend = () => {
recognition.stop();
};
recognition.onerror = (event) => {
console.error('Error occurred in recognition: ' + event.error);
};
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.command === 'changeTab') {
changeTab(message.direction);
}
});
function changeTab(direction) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
chrome.tabs.query({ active: true, currentWindow: true }, (activeTabs) => {
const currentIndex = activeTabs[0].index;
let newIndex;
if (direction === 'next') {
newIndex = (currentIndex + 1) % tabs.length;
} else if (direction === 'previous') {
newIndex = (currentIndex - 1 + tabs.length) % tabs.length;
}
chrome.tabs.update(tabs[newIndex].id, { active: true });
});
});
}