gpt4 book ai didi

javascript - onActiveChanged 每次都不起作用

转载 作者:行者123 更新时间:2023-11-29 20:56:59 25 4
gpt4 key购买 nike

我使用以下数据创建了一个简单的 chrome 扩展程序,但由于某种原因它不能一直工作,有时我需要单击扩展程序按钮才能让它下次在当前选项卡中工作。我不明白为什么......当你点击一个选项卡并激活它时它应该总是有效(即使你创建一个新选项卡 - 它被激活并且应该运行 do-something.js

list .json

{
"manifest_version": 2,

"name": "Test",
"description": "Test",
"version": "1",

"browser_action": {
"default_icon": "icon.png",
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"activeTab",
"tabs"
]
}


背景.js

chrome.tabs.onActiveChanged.addListener(function () {
chrome.tabs.executeScript({
file: 'do-something.js'
});
});


做某事.js

function createNotification() {
var notification = document.createElement('div');
Object.assign(notification.style, {
position: 'fixed',
zIndex: 10000,
textAlign: 'center',
width: '100%',
background: '#f5ae20',
padding: '5px',
top: 0,
left: 0
});
notification.innerHTML = `Test`;
document.body.appendChild(notification);
setTimeout(function() {
notification.remove();
}, 4000);
return notification;
}
createNotification();

为什么它不能一直工作?

最佳答案

您的代码有问题。 do-something.js 应该在 list 文件中提到,否则 chrome 将找不到任何东西,你可以把它作为内容脚本背景脚本网络可访问资源

但是如果你把它作为内容脚本,它会在每次页面加载(根据)你当前的代码时运行。

这是我的方法我将 do-something.js 放在内容脚本中,并在后台 js 和内容脚本之间建立了一个通信 channel ,当它在后台发现事件选项卡已更改时,然后向内容脚本发送消息并显示通知

从后台传递的消息

//listener for detecting tab change
chrome.tabs.onActiveChanged.addListener(function () {
console.log("tab changed");
//query about the active tab and get the tab id
//if you add debug point here it will throw exception because debugger is the current active window , which doesnot have tab
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
//send the message to the content sctipt
chrome.tabs.sendMessage(tabs[0].id, "showNotification", null);//here null is the callback
});
});

内容脚本上的消息接收

chrome.runtime.onMessage.addListener(
function (message, sender, sendResponse) {
//you can receive different type of message here
if (message == "showNotification") {
createNotification();
}
});

我已经为您添加了一个 github 存储库,您可以在那里找到更多详细信息。 https://github.com/pfrng/tabChangeListener

谢谢

关于javascript - onActiveChanged 每次都不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48804939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com