Skip to content

Commit 0099de7

Browse files
committed
open popup in new windows
1 parent f136a5d commit 0099de7

File tree

6 files changed

+125
-55
lines changed

6 files changed

+125
-55
lines changed

popup/index.js

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
Storage,
1616
checkBlackWhiteList,
1717
runScriptInTabWithEventChain,
18+
getLastFocusedTab,
1819
} from "../scripts/helpers/utils.js";
1920
import {
2021
LANG,
@@ -48,6 +49,7 @@ const searchFound = document.querySelector(".search .searchFound");
4849
const scrollToTopBtn = document.querySelector("#scroll-to-top");
4950

5051
let disableSmoothScroll = null;
52+
let isInNewTab = false;
5153

5254
// ========================================================
5355
// ========================= Tabs =========================
@@ -445,9 +447,17 @@ async function runScript(script) {
445447
recentScriptsSaver.add(script);
446448
trackEvent(script.id);
447449

450+
// if (isInNewTab) {
451+
// // focus to targeTab
452+
// await chrome.windows.update(tab.windowId, {
453+
// focused: true,
454+
// });
455+
// }
456+
448457
try {
449-
if (isFunction(script.popupScript?.onClick))
458+
if (isFunction(script.popupScript?.onClick)) {
450459
await script.popupScript.onClick();
460+
}
451461
} catch (e) {
452462
showError(e);
453463
}
@@ -504,13 +514,33 @@ function initTooltip() {
504514
);
505515
openInNewTabBtn.setAttribute(
506516
"data-tooltip",
507-
t({ vi: "Mở trong tab mới", en: "Open in new tab" })
517+
t({ vi: "Mở trong cửa sổ mới", en: "Open in new window" })
508518
);
509519
}
510520

511-
function initSettings() {
521+
const updateTargetTab = UfsGlobal.Utils.debounce(async () => {
522+
let targetTab = await getCurrentTab();
523+
document.title = targetTab?.title || "Useful scripts";
524+
}, 500);
525+
526+
async function initOpenInNewTab() {
527+
let currentTab = await chrome.tabs.getCurrent();
528+
isInNewTab = currentTab != null;
529+
530+
if (isInNewTab) {
531+
[
532+
["tabs", "onHighlighted"],
533+
["windows", "onFocusChanged"],
534+
].forEach(([context, event]) => {
535+
chrome[context][event].addListener(updateTargetTab);
536+
});
537+
538+
openInNewTabBtn.remove();
539+
return;
540+
}
541+
512542
openInNewTabBtn.onclick = async () => {
513-
let exist = await chrome.tabs.query({
543+
const exist = await chrome.tabs.query({
514544
url: location.href,
515545
});
516546
if (exist.length > 0) {
@@ -521,12 +551,12 @@ function initSettings() {
521551

522552
trackEvent("CLICK_OPEN_IN_NEW_TAB");
523553

524-
let width = document.documentElement.clientWidth,
525-
height = document.documentElement.clientHeight,
554+
let width = window.outerWidth,
555+
height = window.outerHeight,
526556
left = window.screenLeft,
527557
top = window.screenTop;
528558

529-
chrome.windows.create({
559+
await chrome.windows.create({
530560
url: location.href,
531561
type: "popup",
532562
height,
@@ -538,7 +568,9 @@ function initSettings() {
538568

539569
window.close();
540570
};
571+
}
541572

573+
function initSettings() {
542574
settingsBtn.onclick = () => {
543575
trackEvent("CLICK_SETTINGS");
544576

@@ -948,6 +980,7 @@ window.addEventListener("scroll", onScrollEnd);
948980
initSearch();
949981
initTooltip();
950982
initSettings();
983+
initOpenInNewTab();
951984
initScrollToTop();
952985
createTabs().then(restoreScroll);
953986

popup/themes/default.less

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@
5252
@border_loading: #3498db;
5353
@border_loading_bg: white;
5454

55+
@body_max_width: 450px;
56+
5557

5658
* {
5759
font-family: @font_family_1;
@@ -66,6 +68,9 @@ body {
6668
color: @color_body;
6769
min-width: 370px;
6870
min-height: 600px;
71+
max-width: @body_max_width;
72+
margin: auto;
73+
position: relative;
6974
}
7075

7176
h1 {
@@ -449,7 +454,7 @@ option {
449454
border-radius: 6px;
450455
padding: 5px;
451456
pointer-events: none;
452-
width: calc(100vw - 40px);
457+
width: calc(100% - 40px);
453458
position: absolute;
454459
z-index: 1;
455460
top: 80%;
@@ -522,6 +527,7 @@ option {
522527
border-radius: 7px;
523528
width: 90%;
524529
max-height: 90%;
530+
max-width: @body_max_width;
525531

526532
.title {
527533
font-size: 18px;

scripts/background-scripts/background_script.js

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const {
1515
const { ISOLATED, MAIN } = chrome.scripting.ExecutionWorld;
1616
const CACHED = {
1717
path: chrome.runtime.getURL("/scripts/"),
18+
lastFocusedWindowIds: [],
1819
activeScriptIds: [],
1920
badges: {},
2021
};
@@ -363,7 +364,6 @@ function listenMessage() {
363364
try {
364365
if (request.action === "ufs-runInBackground") {
365366
const { params = [], fnPath = "" } = request.data || {};
366-
// console.log("runInBackground", fnPath, params);
367367
utils.runFunc(fnPath, params, GLOBAL).then((res) => {
368368
sendResponse(res);
369369
});
@@ -393,6 +393,35 @@ function listenMessage() {
393393
});
394394
}
395395

396+
function listenWindows() {
397+
["onBoundsChanged", "onCreated", "onFocusChanged", "onRemoved"].forEach(
398+
(event) => {
399+
chrome.windows[event].addListener((...details) => {
400+
// listen and cache last window focus
401+
if (event === "onFocusChanged") {
402+
let windowId = details[0];
403+
404+
CACHED.lastFocusedWindowIds.unshift(windowId);
405+
// remove duplicate
406+
for (let i = 1; i < CACHED.lastFocusedWindowIds.length; i++) {
407+
if (windowId === CACHED.lastFocusedWindowIds[i]) {
408+
CACHED.lastFocusedWindowIds.splice(i, 1);
409+
break;
410+
}
411+
}
412+
}
413+
414+
if (event === "onRemoved") {
415+
let index = CACHED.lastFocusedWindowIds.indexOf(details[0]);
416+
if (index >= 0) CACHED.lastFocusedWindowIds.splice(index, 1);
417+
}
418+
419+
runScriptsBackground("windows." + event, null, details);
420+
});
421+
}
422+
);
423+
}
424+
396425
function injectUfsGlobal(tabId, frameId, details) {
397426
[
398427
[["ufs_global.js", "content_script.js"], ISOLATED],
@@ -431,6 +460,7 @@ function main() {
431460
listenNavigation();
432461
listenTabs();
433462
listenMessage();
463+
listenWindows();
434464

435465
chrome.contextMenus.onClicked.addListener(async (info) => {
436466
runScriptsBackground("contextMenus.onClicked", null, info, true);
@@ -443,7 +473,7 @@ function main() {
443473
chrome.runtime.onInstalled.addListener(async function (reason) {
444474
// reasons: browser_update / chrome_update / update / install
445475

446-
if (utils.hasUserId()) {
476+
if (await utils.hasUserId()) {
447477
await trackEvent("ufs-RE-INSTALLED");
448478
}
449479
// create new unique id and save it

scripts/fb_storySaver.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ export default {
1818
let videos = document.querySelectorAll("video");
1919
let listUrls = [];
2020

21-
for (var i = videos.length - 1; i >= 0; i--) {
21+
for (let i = videos.length - 1; i >= 0; i--) {
2222
if (videos[i].offsetHeight === 0) continue;
23-
var reactKey = "";
24-
keys = Object.keys(videos[i]);
25-
for (var j = 0; j < keys.length; j++) {
26-
if (keys[j].indexOf("__reactFiber") != -1) {
27-
reactKey = keys[j].split("__reactFiber")[1];
23+
let reactKey = "";
24+
let keys = Object.keys(videos[i]);
25+
for (let key of keys) {
26+
if (key.indexOf("__reactFiber") != -1) {
27+
reactKey = key.split("__reactFiber")[1];
2828
break;
2929
}
3030
}

scripts/helpers/utils.js

Lines changed: 34 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ const { version } =
77

88
const CACHED = {
99
userID: null,
10-
lastWindowIds: [],
1110
};
1211

1312
export function checkBlackWhiteList(script, url = location?.href) {
@@ -113,16 +112,14 @@ export function runFunc(fnPath = "", params = [], global = {}) {
113112
return p;
114113
});
115114

116-
if (!(typeof fn === "function")) return resolve(null);
115+
if (typeof fn !== "function") return resolve(null);
117116

118117
try {
119118
let res = fn(..._params);
120119

121120
if (!hasCallback) {
122121
if (typeof res?.then === "function") {
123-
res.then?.((_res) => {
124-
resolve(_res);
125-
});
122+
res.then?.(resolve);
126123
} else {
127124
resolve(res);
128125
}
@@ -189,7 +186,6 @@ export async function setActiveScript(scriptId, isActive = true) {
189186
if (isActive) list.push(scriptId);
190187
else list = list.filter((_) => _ != scriptId);
191188
list = list.filter((_) => _);
192-
// localStorage.setItem(listActiveScriptsKey, JSON.stringify(list));
193189
Storage.set(listActiveScriptsKey, list); // save to storage => content script can access
194190
return list;
195191
}
@@ -225,10 +221,6 @@ export async function toggleActiveScript(scriptId) {
225221
// });
226222
// };
227223

228-
// const CACHED = {
229-
// lastWindowId: 0,
230-
// };
231-
232224
// https://developer.chrome.com/docs/extensions/reference/windows/#event-onFocusChanged
233225
// chrome.windows.onFocusChanged.addListener(
234226
// (windowId) => {
@@ -253,47 +245,50 @@ export const getAllTabs = async () => {
253245
return tabs;
254246
};
255247

256-
// Lấy ra tab hiện tại, trong window sử dung gần nhất
257-
if (typeof chrome?.windows?.onFocusChanged?.addListener === "function") {
258-
chrome.windows.onFocusChanged.addListener((windowId) => {
259-
if (windowId !== chrome.windows.WINDOW_ID_NONE) {
260-
CACHED.lastWindowIds.unshift(windowId);
261-
262-
// remove duplicate
263-
for (let i = 1; i < CACHED.lastWindowIds.length; i++) {
264-
if (windowId === CACHED.lastWindowIds[i]) {
265-
CACHED.lastWindowIds.splice(i, 1);
266-
break;
267-
}
268-
}
269-
}
270-
});
248+
export function getPopupURL() {
249+
return chrome.runtime.getURL("/popup/popup.html");
271250
}
272251

273-
export const getCurrentTab = async () => {
274-
let windows = await chrome.windows.getAll({ populate: true });
275-
let lastFocusedWindow = windows
252+
export const getLastFocusedWindowIds = () => {
253+
return chrome.runtime.sendMessage({
254+
action: "ufs-runInBackground",
255+
data: {
256+
fnPath: "getCache",
257+
params: ["lastFocusedWindowIds"],
258+
},
259+
});
260+
};
261+
262+
export const getLastFocusedTab = async () => {
263+
const lastFocusedWindowIds = await getLastFocusedWindowIds();
264+
const windows = await chrome.windows.getAll({ populate: true });
265+
const lastFocusedWindow = windows
276266
// sort windows by lastFocused
277267
.sort(
278268
(a, b) =>
279-
CACHED.lastWindowIds.indexOf(a.id) - CACHED.lastWindowIds.indexOf(b.id)
269+
lastFocusedWindowIds.indexOf(a.id) - lastFocusedWindowIds.indexOf(b.id)
280270
)
281271
// get windows that not popup extension
282-
.filter(
283-
(w) =>
284-
w.type !== "popup" &&
285-
w.tabs[0].url !== chrome.runtime.getURL("/popup/popup.html")
286-
)?.[0];
287-
288-
console.log("lastFocusedWindow", lastFocusedWindow);
272+
.filter((w) => w.type !== "popup" && w.tabs[0].url !== getPopupURL())?.[0];
289273

290274
if (!lastFocusedWindow) return null;
291-
292-
let tab = lastFocusedWindow.tabs.find((tab) => tab.active);
293-
console.log("tabs", tab);
275+
const tab = lastFocusedWindow.tabs.find(
276+
(tab) => tab.active && tab.url !== getPopupURL()
277+
);
294278
return tab;
295279
};
296280

281+
export const getCurrentTab = async () => {
282+
// case normal popup
283+
let tabs = await chrome.tabs.query({
284+
active: true,
285+
currentWindow: true,
286+
});
287+
if (tabs?.[0]?.url !== getPopupURL()) return tabs[0];
288+
289+
return await getLastFocusedTab();
290+
};
291+
297292
export const getCurrentTabId = async () => {
298293
return (await getCurrentTab())?.id;
299294
};

templates/full.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,12 @@ export default {
185185
storage: {
186186
onChanged: (details, context) => {},
187187
},
188+
windows: {
189+
onCreated: (details, context) => {},
190+
onFocusChanged: (details, context) => {},
191+
onBoundsChanged: (details, context) => {},
192+
onRemoved: (details, context) => {},
193+
},
188194
},
189195
};
190196

0 commit comments

Comments
 (0)