I’m building a Chrome Extension and I need users to be able to “detach” the extension from the default top-right location of the popup when they so desire. Note that I still want the extension to open normally when the icon is clicked. But I need that when a specific button is clicked, for the extension to close and immediately open itself in a new window with specified dimensions and no URL address bar as per the below picture:
I’ve got this code so far but it is not working. Nothing happens when the button is clicked:
function createPanel(tab) { if (!tab) return; const contentWindowId = tab.windowId; try { const panelWindowInfo = chrome.windows.create({ url: chrome.runtime.getURL("popup.html"), type:"popup", height: 500, width: 300, }); } catch (error) { console.log(error); } } document.getElementById("myItemX").addEventListener("click", boxX) function boxX() { chrome.action.onClicked.addListener(createPanel); }
What am I missing here?
Advertisement
Answer
I “thinned out” an extension of mine. It should do what you asked and also remember the last position of the detached window.
/*manifest.json - begin*/ { "manifest_version": 3, "name": "xxx", "version": "0.0.0.1", "background": { "service_worker": "sw.js" }, "action": { "default_title": "xxx", "default_icon": "icon.png" }, "icons": { "16": "icon.png" }, "permissions": ["storage", "activeTab"] } /*manifest.json - end*/ /*popup.html - begin*/ <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>xxx</title> <script src="popup.js"></script> </head> <body style="margin:1px 2px 1px 2px; background:#5f9ea0; overflow-y:hidden; min-width:371px"> <div style="margin:0 auto; width:97%; font-size:12px"> <div style="border:1px solid white; margin:3px; display:block"> <div style="padding: 2px; margin: 0px; border: 0px solid red; height: 55px;"> <div id="achPopup" status="" style="width:43px; height: 43px; line-height:21px; border:1px solid black; text-align:center;"> <a>ach<br>Popup</a> </div> </div> </div> </div> </body> </html> /*popup.html - end*/ /*sw.js - begin*/ chrome.action.onClicked.addListener(async t => { await chrome.storage.session.set({'windVal':'popup'}); await chrome.action.setPopup({popup: '../popup.html'}); await chrome.action.openPopup(); }); chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { if (msg.cmd == 'findBestWindow') { let tentativo, wId; let queryOpt = {focused: true}; wId = msg.dp; chrome.windows.get(wId, tentativo => { let rle = chrome.runtime.lastError; if (rle) { wId = msg.ow; chrome.windows.get(msg.ow, tentativo => { if (tentativo.state == 'minimized') queryOpt.state = 'normal'; chrome.action.setPopup({popup: '../popup.html'}, _ => { chrome.windows.update(wId, queryOpt, _ => { chrome.action.openPopup(_ => { sendResponse({'onse': 'OK'}); }) }) }) }) } else { if (tentativo.state == 'minimized') queryOpt.state = 'normal'; chrome.action.setPopup({popup: '../popup.html'}, _ => { chrome.windows.update(wId, queryOpt, _ => { chrome.action.openPopup(_ => { sendResponse({'onse': 'OK'}); }) }) }) } }) } return true }) /*sw.js - end*/ /*popup.js - begin*/ var sndFloatingWind; var rv; function getAllStorage() { return new Promise(ok => { var proms = []; proms.push(chrome.storage.session.get({ 'windVal': 'popup', 'sndFloatingWind': -1 })); proms.push(chrome.storage.local.get({'coords': {'x':1, 'y':1}})); Promise.all(proms) .then(v => { ok({...v[0], ...v[1]}) }) }) } document.addEventListener('DOMContentLoaded', async _ => { function drawComs() { return new Promise(async (ok, ko) => { var frag = new DocumentFragment(); var windVal = rv.windVal; //Detach Popup divEl = document.querySelector('#achPopup'); divEl.firstElementChild.innerText = (windVal == 'popup' ? 'Det' : 'Att') + 'achrnPopup'; divEl.setAttribute('status', windVal); divEl.addEventListener('click', async function() { var precVal = this.getAttribute('status'); var nextVal = (precVal == 'popup' ? 'window' : 'popup'); if (nextVal == 'window') { let w = await chrome.windows.getCurrent({populate: true}); await chrome.storage.session.set({ 'windVal': nextVal, 'sndDockedPopup': w.id}); let itms = await chrome.storage.local.get({'coords': {'x':1, 'y':1}}); let coords = itms.coords; let hN = document.querySelector('html'); w = await chrome.windows.create({ type: 'popup', focused: true, top: coords.y, left: coords.x, height: Math.max(self.outerHeight + 20, hN.scrollHeight + 39), width: Math.max(self.outerWidth, hN.scrollWidth), url: '../popup.html' }); sndFloatingWind = w.id; await chrome.storage.session.set({'sndFloatingWind': sndFloatingWind}); self.close(); } else { await chrome.storage.local.set({'coords': {'x': self.screenX, 'y': self.screenY}}); await chrome.storage.session.set({'windVal': nextVal}); let allWinds = await chrome.windows.getAll({'windowTypes': ['normal']}); allWinds.sort((a, b) => { if (a.id < b.id) return -1 else if (a.id > b.id) return 1 else return 0 }); allWinds.sort((a, b) => { if (a.state == 'minimized') return -1; else return 0 }); let lsw = await chrome.windows.getLastFocused({'windowTypes': ['normal']}); if (lsw?.state != 'minimized') { allWinds.splice(allWinds.find(v => { return v.id == lsw.id }), 1); allWinds.unshift(lsw); } let tmp = await chrome.storage.session.get(['sndFloatingWind', 'sndDockedPopup']); let resp = await chrome.runtime.sendMessage({'cmd': 'findBestWindow', 'fw': tmp.sndFloatingWind, 'dp': tmp.sndDockedPopup, 'ow':allWinds[0].id }) if (resp.onse == 'OK') self.close(); else if (resp.err) alert(risp.err); } }); ok() }) } rv = await getAllStorage(); if (rv.windVal == 'popup') { if (rv.sndFloatingWind != -1) { try { let w = await chrome.windows.get(rv.sndFloatingWind); if (typeof w !== 'undefined') await chrome.windows.remove(rv.sndFloatingWind); await chrome.storage.session.clear('sndFloatingWind') } catch(err) {} } } await drawComs() }); chrome.action.setPopup({popup: ''}) /*popup.js - end*/