forked from GoogleChrome/chrome-extensions-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent_script.js
56 lines (50 loc) · 1.37 KB
/
content_script.js
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
/**
* Copyright (c) 2011 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
var speakKeyStr;
function speakSelection() {
var focused = document.activeElement;
var selectedText;
if (focused) {
try {
selectedText = focused.value.substring(
focused.selectionStart, focused.selectionEnd);
} catch (err) {
}
}
if (selectedText == undefined) {
var sel = window.getSelection();
var selectedText = sel.toString();
}
chrome.extension.sendRequest({'speak': selectedText});
}
function onExtensionMessage(request) {
if (request['speakSelection'] != undefined) {
if (!document.hasFocus()) {
return;
}
speakSelection();
} else if (request['key'] != undefined) {
speakKeyStr = request['key'];
}
}
function initContentScript() {
chrome.extension.onRequest.addListener(onExtensionMessage);
chrome.extension.sendRequest({'init': true}, onExtensionMessage);
document.addEventListener('keydown', function(evt) {
if (!document.hasFocus()) {
return true;
}
var keyStr = keyEventToString(evt);
if (keyStr == speakKeyStr && speakKeyStr.length > 0) {
speakSelection();
evt.stopPropagation();
evt.preventDefault();
return false;
}
return true;
}, false);
}
initContentScript();