我正在尝试在单击的扩展程序按钮页面上分配的特定选项卡上运行一些脚本。
例如,如果我单击 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 并使该代码在此选项卡上运行。我该怎么做?
最佳答案
在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作为参数一样,它已经获得了当前窗口中的事件选项卡。我还添加了 tabs 权限以获得 tabs[0].url
属性。无论如何,通过这种方式,当您获取标签的 tabId 和 url 属性时,您可以更好地控制要操作的标签。
关于javascript - Chrome 扩展程序在特定选项卡上运行该进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698147/