Chrome扩展在继续下一行之前等待chrome.storage.local.get。

huangapple go评论66阅读模式
英文:

chrome extension wait for chrome.storage.local.get before proceeding to next line

问题

Here is the translated code:

我在使用 `chrome.storage.local.get` 时遇到同步问题

可行的代码如下

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('chrome.runtime.onMessage.addListener: ', message)
    if (message.type === "NewURL") {
        console.log('background.js: 启动计时器')
        let blockUrlList = ["youtube.com", "dict.cc"]
        /*
        chrome.storage.local.get(["block_urls"], (res) => {
            blockUrlList = "block_urls" in res ? res.block_urls : []
        })
        */
        console.log(blockUrlList)
        chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
            tabs.forEach((tab) => {
                console.log('tab.id: ', tab.id, 'tab.url:', tab.url)
            })
        })
    }
})

然而如果我尝试从 chrome 存储中获取 blockUrlList我得到了一个空列表

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('chrome.runtime.onMessage.addListener: ', message)
    if (message.type === "NewURL") {
        console.log('background.js: 启动计时器')
        let blockUrlList = []
        
        chrome.storage.local.get(["block_urls"], (res) => {
            blockUrlList = "block_urls" in res ? res.block_urls : []
        })
        
        console.log(blockUrlList)
        chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
            tabs.forEach((tab) => {
                console.log('tab.id: ', tab.id, 'tab.url:', tab.url)
            })
        })
    }
})

如何在进行 chrome.storage.local.get 之前同步以及如何使 chrome.tabs.query 在进行下一行之前等待

**编辑**
虽然问题已由管理员关闭但我将写出我学到的最干净易于阅读的解决方案

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === "NewURL") {
        injectJS()
    }
})
async function injectJS() {   
    try {
        let blockUrlList = []
        const res = await chrome.storage.local.get(["block_urls"])
        blockUrlList = "block_urls" in res ? res.block_urls : []
        
        const qryOptions = { "url": blockUrlList.map(p => `*://*.${p}/*`)}
        const tabs = await chrome.tabs.query(qryOptions)

        tabs.forEach((tab) => {
            chrome.scripting.executeScript({
                target: {tabId: tab.id},
                files: ['content/injected.js']
            })
        })
    } catch (err) {
        console.log('没有匹配的标签', err)
    }
}

Please note that the translation contains the code portions and omits the parts where you mentioned not to provide additional content. If you have any more specific questions or need further assistance, please feel free to ask.

英文:

I am having syncronization problem with chrome.storage.local.get

The code that works:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('chrome.runtime.onMessage.addListener: ', message)
if (message.type === "NewURL") {
console.log('background.js: start timer')
let blockUrlList = ["youtube.com", "dict.cc"]
/*
chrome.storage.local.get(["block_urls"], (res) => {
blockUrlList = "block_urls" in res ? res.block_urls : []
})
*/
console.log(blockUrlList)
chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
tabs.forEach((tab) => {
console.log('tab.id: ',tab.id, 'tab.url:', tab.url)
})
})
}
})

however, if i try to get blockUrlList from chrome storage I get blank list.

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('chrome.runtime.onMessage.addListener: ', message)
if (message.type === "NewURL") {
console.log('background.js: start timer')
let blockUrlList = []
chrome.storage.local.get(["block_urls"], (res) => {
blockUrlList = "block_urls" in res ? res.block_urls : []
})
console.log(blockUrlList)
chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
tabs.forEach((tab) => {
console.log('tab.id: ',tab.id, 'tab.url:', tab.url)
})
})
}
})

How can I synchronise i.e. wait for chrome.storage.local.get before proceeding to chrome.tabs.query?
Also I want chrome.tabs.query to wait on it before proceeding to next line

EDIT
Though the question has been closed by the moderator. I am writing the cleanest (easiest to read) solution I learned.

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "NewURL") {
injectJS()
}
})
async function injectJS() {   
try {
let blockUrlList = []
const res = await chrome.storage.local.get(["block_urls"])
blockUrlList = "block_urls" in res ? res.block_urls : []
const qryOptions = { "url": blockUrlList.map(p => `*://*.${p}/*`)}
const tabs = await chrome.tabs.query(qryOptions)
tabs.forEach((tab) => {
chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ['content/injected.js']
})
})
} catch (err) {
console.log('No matching tab', err)
}
}

答案1

得分: 1

您可以简单地将其放入回调函数中:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('chrome.runtime.onMessage.addListener: ', message)
    if (message.type === "NewURL") {
        console.log('background.js: start timer')
        let blockUrlList = []
        
        chrome.storage.local.get(["block_urls"], (res) => {
            blockUrlList = "block_urls" in res ? res.block_urls : []
            console.log(blockUrlList)
            chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
                tabs.forEach((tab) => {
                    console.log('tab.id: ',tab.id, 'tab.url:', tab.url)
                })
            })
        })
        
    }
})

回调函数会在您首选的时刻运行,即在 get() 成功完成后运行。

英文:

You can simply put it into the callback:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('chrome.runtime.onMessage.addListener: ', message)
if (message.type === "NewURL") {
console.log('background.js: start timer')
let blockUrlList = []
chrome.storage.local.get(["block_urls"], (res) => {
blockUrlList = "block_urls" in res ? res.block_urls : []
console.log(blockUrlList)
chrome.tabs.query({ "url": blockUrlList.map(p => `*://*.${p}/*`)}, (tabs) => {
tabs.forEach((tab) => {
console.log('tab.id: ',tab.id, 'tab.url:', tab.url)
})
})
})
}
})

The callback, after all is running at the very moment of your preference, i.e., when the get() has finished successfully.

huangapple
  • 本文由 发表于 2023年5月6日 23:20:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定