Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
69 lines (63 loc) · 1.97 KB
/
Copy pathbackground.js
File metadata and controls
69 lines (63 loc) · 1.97 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
function toggleVideoPiP() {
const video = document.querySelector('video');
if (!video) return { found: false };
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
return { found: true, action: 'exit' };
}
video.requestPictureInPicture();
return { found: true, action: 'enter' };
}
function enterVideoPiP() {
const video = document.querySelector('video');
if (!video || video.paused) return { found: false };
if (document.pictureInPictureElement) return { found: true, action: 'already' };
video.requestPictureInPicture();
return { found: true, action: 'enter' };
}
async function executePiPToggle(tab) {
try {
const [result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: toggleVideoPiP
});
return result && result.result;
} catch (err) {
return null;
}
}
async function executePiPEnter(tabId) {
try {
const [result] = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: enterVideoPiP
});
return result && result.result;
} catch (err) {
return null;
}
}
chrome.commands.onCommand.addListener(async (command) => {
if (command === 'toggle-pip') {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) await executePiPToggle(tab);
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'togglePiP') {
chrome.tabs.query({ active: true, currentWindow: true }, async ([tab]) => {
if (!tab) { sendResponse({ success: false }); return; }
const result = await executePiPToggle(tab);
sendResponse({ success: true, ...result });
});
return true;
}
if (message.action === 'autoEnterPiP') {
const tabId = sender.tab ? sender.tab.id : null;
if (!tabId) { sendResponse({ success: false }); return; }
executePiPEnter(tabId).then(function(r) {
sendResponse({ success: true, ...r });
});
return true;
}
});