Considere este código:
// background.js function Action(tab) { let title; function domTitle() { return document.title; } chrome.scripting.executeScript({target: {tabId: tab.id}, func: domTitle}, injectionResults => { for (const frameResult of injectionResults) { this.title = frameResult.result; console.log(this); // line 10 console.log(this.title); // line 11 } }); } chrome.contextMenus.onClicked.addListener(((info, tab) => { const action = new Action(tab); console.log(action); // line 29 console.log(action.title); // line 30 }));¿Por qué la línea 30 (el título de propiedad del título de Acción) no está definida? La propiedad ha sido claramente establecida.
¿Como arreglarlo? Entonces, la línea 30 contendrá el valor establecido por chrome.scripting.executeScript.
Prácticamente todas las funciones de chrome.* de las nuevas promesas de retorno de la API del manifiesto v3.
Aquí está mi solución:
// background.js const contextMenu = () => { chrome.contextMenus.create({ "id": "myIdContextMenu", "title": "My Context Menu Title", "documentUrlPatterns": [ "http://*/*", "https://*/*" ] }); }; async function getValues(tab) { function domTitle() { return document.title; } const dom = chrome.scripting.executeScript({target: {tabId: tab.id}, func: domTitle}) .then(result => {return {name: "cookies", values: result}}); const cookies = chrome.cookies.getAll({domain: "google.com"}) .then(result => {return {name: "dom", values: result}}); return await Promise.all([cookies, dom]); } chrome.contextMenus.onClicked.addListener((info, tab) => { getValues(tab).then(values => { console.log(values); // Rest of my logic here. }) .catch(error => { console.error(error.message) }); }); chrome.runtime.onStartup.addListener(contextMenu); chrome.runtime.onInstalled.addListener(contextMenu);