由于某种原因,我的
executeScript
功能无法正常工作。
这是我的代码:
async function scrape_get_url(){
console.log("Getting url: " + from_url);
var tab_id;
chrome.tabs.create({ "url": from_url}, function(newTab){
tab_id = newTab.id;
console.log("Checking for tab url update");
});
chrome.tabs.onUpdated.addListener( function(tabId, info) {
if(tabId == tab_id && info.url){
console.log("Executing scrape script");
console.log("tab id:" + tab_id);
console.log("updated tab url:" + info.url);
chrome.scripting.executeScript({
target: {tabId: tab_id},
function: scrape
});
}
});
}
function scrape(){
console.log("Getting Element...");
}
这是我的输出:
Getting url: https://developer.chrome.com/docs/extensions/mv3/getstarted
Checking for tab url update
Executing scrape script
tab id:293
updated tab url:https://developer.chrome.com/docs/extensions/mv3/getstarted/
由于 chrome bug,我有一个
onUpdated
监听器,如here所述。另外,我将 onUpdated
函数放在 create
函数回调之外的原因是因为根据 StackOverflow 上的另一个问题(我再也找不到了 :/ ),将 executeScript
放在 create
中的回调不会运行脚本。
我的权限在清单文件中设置正确。
我看到了 chromium bug 报告,并深入研究了这一点。
我没有解决方案,我有一个可行的方法。
function _func(res){
setTimeout( () => {
// Do things with the page.
}, 3000);
}
chrome.tabs.create({url: 'https://www.example.com'}).then((tab) => {
setTimeout(() => {
chrome.scripting.executeScript({
target: {tabId: tab.id},
func: _func //,
// I used args in my case, you dont have to. args: [msg.content]
})
}, 3000)
});
记住 chrome.scripting 需要指定权限:['script']