1

我正在创建一个扩展,它将基于突出显示的文本启动一个外部脚本。所以,到目前为止,脚本工作,除了我在关闭新创建的窗口时遇到问题。

在我的 background.html 中,我有以下内容:

<script>
function executeScript(selection) {
  var queryText = 'script:' + selectedText;
  chrome.tabs.create({url: queryText});
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.remove(tab.id);
  });
}
</script>

我的问题是上面的设置,它在“url”加载之前关闭了选项卡,所以它永远不会执行脚本。

如果我取出 getSelected 行(第 5-7 行),它会打开选​​项卡并完美运行脚本。我试图让语法在执行后自动关闭选项卡。

谢谢!

4

3 回答 3

1

这对我有用:

chrome.tabs.create({ url: yourUrl },function(tab){
                                                setTimeout(function(){chrome.tabs.remove(tab.id);}, 200);
                                    });
于 2013-08-22T13:37:39.730 回答
1

不完全确定您要完成什么,但如果您想在脚本运行后关闭选项卡,您应该让脚本使用 .html 向 background.html 发送“关闭我”请求chrome.extension.sendRequest

您最好使用chrome.tabs.executeScript,它允许您传递一个函数(您可以在其中关闭选项卡),该函数在脚本完成运行后被调用。

于 2010-06-24T19:32:16.033 回答
1

I would like to post a followup question to this issue:

I want to make a Chrome Extension which passes on the URL (and eventually a selected Text) of a given Tab to my program (in OS X).

The problem is that Chrome closes the tab immediately after it opened it and does not really load the URL. The only way to make this happen is by inserting the alert-command, which is not practicable.

I also tried it with

chrome.tabs.onCreated.addListener

but it's the same result, and setTimeout does not seem to be registered at all.

My code:

chrome.browserAction.onClicked.addListener(function(tab) { chrome.tabs.create({url:"myApp:add?url="+encodeURIComponent(tab.url)}, function(tab){ alert("Your URL is added to myApp"); chrome.tabs.remove(tab.id); }); });

I would need the exact same result, only without the alert box.... thank you for your help!

于 2011-02-09T15:17:29.687 回答