我正在尝试在扩展按钮单击的页面上指定的spesific选项卡上运行一些脚本。
例如,如果我单击popup.html上的按钮,它应该只在这个页面上运行到脚本的末尾,即使我切换到另一个选项卡。
我的算法是这样的:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
//Some other processes
chrome.tabs.getSelected(null,function(tabS) {
//Some other processes
chrome.tabs.executeScript(null, {file:"some_js.js"});
});
});我在页面上使用了一些DOM操作。如果切换到另一个选项卡,进程将被中断,因为它侦听当前选项卡。我想为进程选项卡分配一个id,并使这些代码在此选项卡上工作。我该怎么做呢?
发布于 2019-02-14 21:32:03
在popup.html中添加一个按钮元素。然后将此代码添加到popup.js中
function handleClick (e) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.executeScript(tabs[0].id,
{ code: `setInterval(function () { console.log('This event is running only at the tab with domain: ${tabs[0].url} after 1000ms') }, 1000)` })
})
}
document.addEventListener('DOMContentLoaded', function () {
const button = document.getElementById('popup-button')
button.addEventListener('click', handleClick)
});单击该按钮时,该代码将仅在该特定选项卡中执行。您将能够在开发人员控制台中看到该消息。
代码还可以是扩展名中的另一个JS文件。就像你在问题中那样。
chrome.tabs.query在这里并不是必要的,就好像您执行chrome.tabs.executeScript传递null作为参数一样,它已经在当前窗口中获得了active选项卡。为了获得tabs[0].url属性,我还添加了选项卡权限。无论如何,这样您就可以更好地控制您在获取它们的tabId和url属性时所操作的选项卡。
https://stackoverflow.com/questions/54698147
复制相似问题