在我想要的之前调用 chrome.tabs.executeScript 的回调,需要解决方法
我在 Google Chrome 中编写了一个扩展程序,可以打开网页选项卡并将代码注入该页面。我还在 chrome.tabs.executeScript 中注册了一个回调,以便在代码完成后调用。然后,此回调将另一个选项卡打开到另一个页面并执行其他操作,但我不希望在第一个选项卡的页面被操作之前发生这种情况。
我的问题是,这个回调在应该被调用的时候被调用,而不是在我希望它被调用的时候被调用:
我注入的代码包含一个 setInterval
,它在执行操作之前检查是否存在某些 DOM 元素页面上,并且我不希望在这些 DOM 元素被执行之前激活回调。
我不知道有什么方法可以让注入的代码与我的扩展页面中的代码进行交互。
有什么方法可以告诉我的扩展页面中的代码可以继续并在正确的时间调用回调吗?
下面是一些代码,解释了我现在正在做的事情:
function doStuffWithTabs() {
chrome.tabs.create({url: 'some/url/here'}, function(tab) {
chrome.tabs.executeScript(tab.id, code: "var interval = setInterval(function(){if(jQuery(domElement).length){clearInterval(interval);workMagic();}},1);"}, function(){
goForthAndConquer();
});
}
}
workMagic()
表示操作打开的选项卡的 DOM 的代码,而 goForthAndConquer()
是我想要发生的事情当打开的选项卡的操作完成时。
现在,正如您所看到的,注入的代码只是注册了 setInterval 并立即调用回调。同样,我希望回调发生在 workMagic()
之后。
I have written an extension in Google Chrome that opens a tab to a webpage and injects code into that page. I have also registered a callback in chrome.tabs.executeScript
to be called after the code's completion. This callback then opens another tab to another page and performs other actions, but I don't want that to happen until the first tab's page has been manipulated.
My issue is that this callback is called when it should be called, but not when I want it to be called:
My injected code contains a setInterval
that checks to see if certain DOM elements are present before acting on the page, and I don't want the callback to activate until those DOM elements have been acted on.
I don't know of any way to have the injected code interact with the code in my extension page.
Is there any way to tell the code in my extension page that it's okay to keep going and call the callback at the right time?
Here's some code that explains what I'm doing now:
function doStuffWithTabs() {
chrome.tabs.create({url: 'some/url/here'}, function(tab) {
chrome.tabs.executeScript(tab.id, code: "var interval = setInterval(function(){if(jQuery(domElement).length){clearInterval(interval);workMagic();}},1);"}, function(){
goForthAndConquer();
});
}
}
workMagic()
represents the code that manipulates the DOM of the opened tab and goForthAndConquer()
is what I want to happen when the manipulation of the opened tab is complete.
Right now, as you can plainly see, the injected code just registers the setInterval and immediately calls the callback. Again, I want the callback to happen after workMagic()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要分两步完成。
script.js:
背景.html:
You need to do it in two steps.
script.js:
background.html: