获取当前标签并将其传递给Chrome扩展程序中的变量 [英] Get current tab and pass it to variable in a Chrome Extension
问题描述
函数tabURL(){
var url =;
chrome.tabs.getSelected(null,function(tab){url = tab.url;});
返回网址;
}
当我使用时:
chrome.tabs.getSelected(null,function(tab){alert(tab.url);});
Chrome会显示网址,但如果我在Chrome控制台中使用我的功能,函数会返回 。
有没有办法将tab.url传递给一个变量然后返回这个变量?
chrome.tabs.getSelected
是异步。这意味着当调用回调函数时, return url
已经发生。
两个选项来达到预期的效果。正确地重写你的代码,正确地实现异步方面(确切的细节取决于您的扩展的实现)。
请注意, getSelected
已被已弃用并替换为 chrome.tabs.query
自Chrome 16以来。 当前使用 chrome.tabs.onUpdated
(添加tabID + URL),
chrome.tabs.onRemov ed
(删除过时的条目)和 chrome.tabs.onActivated
(设置当前活动选项卡)。
2的代码:
$ b
//我们的哈希
var tabIdToURL = {};
var currentTabId = -1;
//将更改添加到散列(制表符选项卡的页面加载)
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
tabIdToURL [tabId] = tab .url; //也可以用tab.id和changeInfo.url
});
//从已关闭的标签中删除条目
chrome.tabs.onRemoved.addListener(function(tabId){
delete tabIdToURL [tabId];
});
//设置当前活动标签的ID
chrome.tabs.onActivated.addListener(function(activeInfo){
currentTabId = activeInfo.tabId;
});
//基于问题函数的用法
函数getURL(){
return tabIdToURL [currentTabId] || ;
}
I'm trying to create a function that returns the current tab url:
function tabURL() {
var url="";
chrome.tabs.getSelected(null, function(tab) {url = tab.url;});
return url;
}
When I use:
chrome.tabs.getSelected(null, function(tab) {alert(tab.url);});
Chrome shows the url, but if I use my function inside the chrome console, the function returns "".
Is there a way to pass the tab.url to a variable and then return this variable?
chrome.tabs.getSelected
is asynchronous. That means that when the callback function is called, return url
"has already occurred".
You've got two options to achieve the desired effect.
Properly rewrite your code, to correctly implement the asynchronous aspect (the exact details depends on your extension's implementation).
Note thatgetSelected
has been deprecated and replaced withchrome.tabs.query
since Chrome 16.Maintain a hash with the current URLs using
chrome.tabs.onUpdated
(add tabID + URL),chrome.tabs.onRemoved
(to remove obsolete entries) andchrome.tabs.onActivated
(to set the current active tab).
Code for 2:
// Our hash
var tabIdToURL = {};
var currentTabId = -1;
// Add changes to the hash (tab creation, tab's page load)
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
tabIdToURL[tabId] = tab.url; // also available as tab.id and changeInfo.url
});
// Remove entries from closed tabs
chrome.tabs.onRemoved.addListener(function(tabId) {
delete tabIdToURL[tabId];
});
// Set the ID of the current active tab
chrome.tabs.onActivated.addListener(function(activeInfo) {
currentTabId = activeInfo.tabId;
});
// Usage, based on the question's function
function getURL() {
return tabIdToURL[currentTabId] || '';
}
这篇关于获取当前标签并将其传递给Chrome扩展程序中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!