我正在创建Chrome的扩展程序,可以打开新标签页,放大/缩小当前页面...但我无法理解chrom.tabs.getZoom()和chrome.tabs.setZoom()的工作方式和如何使用它们。 这是我的代码,你能帮帮我吗?
/*Important when add envent click for button*/
zoomStep = 1.1;
tabId = -1;
document.addEventListener('DOMContentLoaded', function () {
//getting tab's id
chrome.tabs.query({ active: true }, function (tabs) {
if (tabs.length > 1)
console.log('[ZoomDemoExtension] Query unexpectedly returned more than 1 tab.');
tabId = tabs[0].id;
chrome.tabs.getZoom(tabId, 100);
});
document.getElementById('btnZoomIn').addEventListener('click', FncZoomIn);
document.getElementById('btnZoomOut').addEventListener('click', FncZoomOut);
document.getElementById('btnClose').addEventListener('click', FncClose);
document.getElementById('btnNewTab').addEventListener('click', FncNewTab);
document.getElementById('btnReset').addEventListener('click', FncReset);
})
function changeZoomByFactorDelta(factorDelta) {
//if (tabId == -1)
// return;
//alert(tabId);
var currentRatio = 1;
var ratio = 1000;
currentRatio = ratio / 100;
chrome.tabs.query({ windowId: chrome.windows.WINDOW_ID_CURRENT, active: true }, function (tabs) {
zoomtab(tabs[0], ratio / 100);
});
}
function FncZoomIn(e) {
//window.open("https://www.google.com.vn/");
chrome.tabs.getZoom(tabId, function (event) {
chrome.send('defaultZoomFactorAction',
[String(1.5)]);
});
}
function FncClose(e) {
self.close();
}
function FncNewTab(e) {
window.open("chrome://newtab");
}
答案 0 :(得分:1)
你需要在回调函数中获取缩放因子
chrome.tabs.query({ active: true }, function (tabs) {
tabId = tabs[0].id;
chrome.tabs.getZoom(tabId, function (zoomFactor) {
console.log(zoomFactor); //or alert(zoomFactor);
});
});
日志将在后台页面中(它将以1或1.25格式缩放)
修改强>
顺便说一句。标签API无法在内容脚本中访问,仅在后台/扩展脚本中可访问。您的文档包装器是错误的。尝试使用工具栏按钮测试代码。包裹在
chrome.browserAction.onClicked.addListener
而不是DOMContentLoaded
编辑2 (我希望我不会为此而受到抨击)
清单
{
"manifest_version": 2,
"name": "getZoom() test",
"version": "0.1",
"background": {"scripts": ["background.js"]},
"browser_action": {"default_icon": "icon.png"},
"permissions" : ["tabs"]
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.query({ active: true }, function (tabs) {
tabId = tabs[0].id;
chrome.tabs.getZoom(tabId, function (zoomFactor) {
alert(zoomFactor);
});
});
});
工具栏上的 btn点击,你会得到当前标签的缩放系数...从这样的东西开始,然后在其中介绍你的想法
*在您的文件夹中放置一些16x16 px icon.png按钮