gpt4 book ai didi

javascript - Chrome.ExecuteScript 问题

转载 作者:行者123 更新时间:2023-11-30 16:02:12 25 4
gpt4 key购买 nike

目前我正在使用以下代码将警报语句注入(inject)网页,打印出我传入的变量。脚本如下:

  //Inject statement setting the variable "count" in the webpage to 5
chrome.tabs.executeScript(id, {
code: 'count = 5;'
});

//Inject the script that simply alerts the variable count (alert(count);)
chrome.tabs.executeScript(id, {
file: 'inject.js'
});

//Inject statement setting the variable "count" in the webpage to 5+1
chrome.tabs.executeScript(id, {
code: 'count++;'
});

//Inject the script that simply alerts the variable count (alert(count);)
chrome.tabs.executeScript(id, {
file: 'inject.js'
});

理想情况下,我希望得到先提示“5”然后提示“6”的结果。但是,尽管我在代码中增加了变量“count”,但网页在两个语句中都只警告“5”。我是对 chrome.tabs.executeScript 有什么误解,还是忽略了一个简单的错误?

最佳答案

请注意 chrome.tabs.executeScript 是一个异步调用,这意味着在您调用 chrome.tabs.executeScript(id, {code: 'count++;'});count 的值可能尚未更新,因此结果将是 56

chrome.tabs.executeScript有一个回调,在 JavaScript 执行后调用。您可以将您的方法包装在其中。

chrome.tabs.executeScript(id, {code: 'count++;'}, () => chrome.tabs.executeScript(id, {file: 'inject.js'}));

关于javascript - Chrome.ExecuteScript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37558529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com