我正在创建一个 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");
}
最佳答案
您需要在回调函数中获取缩放系数
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(我希望我不会因此而受到批评)
list
{
"manifest_version": 2,
"name": "getZoom() test",
"version": "0.1",
"background": {"scripts": ["background.js"]},
"browser_action": {"default_icon": "icon.png"},
"permissions" : ["tabs"]
}
背景.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
关于javascript - 如何通过Chrome API在Chrome浏览器中缩放页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25156714/