Estoy tratando de hacer que 'get_current_url' funcione con redux-saga Por cierto, he estado haciendo una extensión de Chrome con react js. Entonces, tengo que usar chrome.tabs.query api para obtener el uri actual Aquí está mi código
import { Action } from "redux"; import { call, fork, put, takeEvery, takeLatest } from "redux-saga/effects"; import { all } from "redux-saga/effects"; import { timeActions } from "./timeSlice"; function getUrlApi() { const queryInfo = { active: true, currentWindow: true }; let currentUrl: string = ''; chrome.tabs.query(queryInfo, (tabs: chrome.tabs.Tab[]) => { const id = tabs[0].id; chrome.tabs.sendMessage(id || 0, "GET_URL", (res: any) => { console.log(res); // ---> res.url will be receive data currentUrl = res.url; // I wanna allocate this data to currentUrl and return but there is something kind of lexical problem }) }); return currentUrl; } function* getUrl() { try { const test: string = yield getUrlApi(); // ---> always get undefined // yield timeActions.getUrlSuccess(); } catch (err) { yield put(timeActions.getUrlFail(err)); } } function* watchGetUrl() { yield takeLatest(timeActions.getUrl, getUrl); } export function* timeSaga() { yield all([fork(watchGetUrl)]); }Como puede ver, estoy tratando de asignar datos de res.url a currentUrl; Pero, hay algo problema léxico. Como consecuencia, siempre regresa indefinido; Como puedó resolver esté problema. Gracias
El problema es que las funciones de Chrome API son asíncronas, por lo que regresa de la función antes de que se procesen.
La API de Chrome admite promesas, que son mucho más fáciles de manejar con las sagas, por lo que sugiero usarlas en su lugar.
async function getUrlApi() { const queryInfo = { active: true, currentWindow: true }; const tabs = await chrome.tabs.query(queryInfo); const id = tabs[0].id; const res = await chrome.tabs.sendMessage(id || 0, "GET_URL"); console.log(res); return res.url; }