Sve*_*ter 4 tabs google-chrome google-chrome-extension
我是编程chrome扩展的新手,这将是我的第一个扩展.
我想要的:现在我想为页面做一个pageAction,如果显示某个html标签.要做一个pageAction,似乎我必须知道当前选项卡的TabID,所以我尝试了这个,这不起作用(参见代码中的注释):
manifest.json(工作正常,只是为了向您展示我的清单的样子)
{
"manifest_version":2,
"name":"ExtensionName",
"description":"Description",
"version":"1.0",
"page_action":{
"default_icon":"icon.png",
},
"content_scripts":[
{
"matches":[
"http://www.domain.com/page.aspx"
],
"js":["searchTag.js"],
"run_at":"document_idle",
"all_frames":false
}
]
}
Run Code Online (Sandbox Code Playgroud)
searchTag.js(代码或多或少像Arithmomaniac一样回答如何从后台页面获取当前tabId)
if (document.getElementById("idIWant")) {
var currentTab;
alert(currentTab); //this works and gives an alert with "undefined"
//now the alert in the function callback doesn't work
chrome.tabs.query(
{currentWindow: true, active: true},
function(tabArray) {
alert(tabArray[0].id);
currentTab = tabArray[0].id;
}
)
}
Run Code Online (Sandbox Code Playgroud)
那我的代码出了什么问题?看来我没有正确使用chrome.tabs.query(),但我没有看到它.
searchTag.js是一个内容脚本(https://developer.chrome.com/extensions/content_scripts.html),它无法访问chrome.tabsAPI.您必须从内容脚本向后台页面(https://developer.chrome.com/extensions/messaging.html)发送消息,并在后台页面中调用chrome.tabs.query.例如:
searchTag.js
if (document.getElementById("idIWant")) {
chrome.runtime.sendMessage('showPageAction');
}
Run Code Online (Sandbox Code Playgroud)
bg.js
var currentTab;
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request == 'showPageAction') {
chrome.tabs.query(
{currentWindow: true, active: true},
function(tabArray) {
if (tabArray && tabArray[0])
chrome.pageAction.show(tabArray[0].id);
}
);
// sender will also contain the tab id so you can simply use
// if (sender)
// chrome.pageAction.show(sender.tab.id);
}
});
Run Code Online (Sandbox Code Playgroud)
并将其添加到manifest.json中
"background": {
"scripts": ["bg.js"],
"persistent": true
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3046 次 |
| 最近记录: |