我想将选项卡更改为下一个,在那里对HTML进行一些操作(例如获取一些数据),然后返回“主”选项卡。总是打开两个选项卡。我可以更改选项卡(使用background.js),它应该处于活动状态,但是当我尝试获取html时,它始终会获取background.html ...有没有办法从第二个选项卡获取html代码?我想我也可以“返回上一个标签”,所以我真正需要的是:从第二个标签获取html!(如果可能,我可以在html上执行操作吗?)
manifest.json
{
"manifest_version": 2,
"name": "name",
"description": "desc.",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"content_scripts" :[
{
"matches":[
"http://www.thecrims.com/*"
],
"js":["contentscript.js"]
}
],
"permissions": [
"http://www.thecrims.com/*",
"https://www.thecrims.com/*",
"background",
"tabs"
],
"browser_action": {
"default_icon": "icon.jpg"
}
}
从contentscript.js到background.js的调用
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response);
});
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
{
chrome.windows.getLastFocused(
// Without this, window.tabs is not populated.
{populate: true},
function (window)
{
var foundSelected = false;
for (var i = 0; i < window.tabs.length; i++)
{
// Finding the selected tab.
if (window.tabs[i].active)
{
foundSelected = true;
}
// Finding the next tab.
else if (foundSelected)
{
// Selecting the next tab.
chrome.tabs.update(window.tabs[i].id, {active: true, selected: true});
//GET HTML FROM ^
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
console.log(tabs[0]);//this give me BACKGROUND.HTML html... i want from tabs[0]!!
});
return;
}
}
});
sendResponse({farewell: "goodbye"});
}
});
我想您正在尝试从开发工具中运行此程序,以打开背景页面。
然后,活动窗口(由询问tabs.query
)将与具有单个选项卡的“开发工具”窗口完全相同。
您为什么还要运行query
?您已经有选项卡window.tabs[i]
,可以使用代替tabs[0]
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句