javascript - Chrome 扩展 : How do I get current tabs title and assign string to variable?

标签 javascript google-chrome-extension

我正在尝试使用扩展程序获取 chrome 中当前选项卡的标题,然后将返回的字符串分配给一个变量。我设法使用 tabs[0].title 获得了标题,但我无法将该标题分配给新的字符串变量。

这是代码:

var address;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    var title = tab.title;

    console.log("Title: " + title);
    address = title;
});

console.log("Address:" + address);

console.log("Title: "+ title); 显示 tab.title 按预期工作,但是,当我尝试分配标题时字符串到新变量 (address) 当行 console.log("Address:"+ address); 返回 "Address:Undefined 时显示它不起作用".

我还尝试在第一行中将变量 address 创建为空字符串。这看起来像:var address = new String();

我查看了这里并查看了文档,但找不到我遇到的问题的答案。

最佳答案

您将需要使用回调函数。请参阅下面的示例。

var address;

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    var tab = tabs[0];
    var title = tab.title;

    console.log("Title: " + title);
    address = title;
    print_address(address);
});

function print_address(address) {
    console.log("Address:" + address);
}

关于javascript - Chrome 扩展 : How do I get current tabs title and assign string to variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49295546/

相关文章:

javascript - 使用 Javascript 读取环境变量

javascript - Chrome 扩展程序无法同时编辑主页上的 DIV 和 iFrame 页面内的 DIV

javascript - 设置扩展程序的键盘快捷键时出错

google-chrome - Chrome : Install extension(crx) manually doesn't work anymore

javascript - 链接到 chrome ://history through extension

javascript - 使用逗号值作为饼图中的数据点

javascript - 从倒数第二个开始删除表格行

javascript - 如何在页面加载时运行 Javascript

javascript - setInterval 在 Google Chrome 扩展程序中不起作用(仅触发一次)

javascript - Angular 6 测试 Jasmine Karma : Override Provider Not working