我想做一个小扩展,将一个简单的 html 注入到视频正下方的 YouTube 页面中。如果我简单地访问 YouTube 网址,它就可以正常工作。但是,如果我从 youtube 提供的视频中选择一个视频,那么我的 html 代码会被注入两次,但会被删除。我可以看到它几乎立即出现然后消失。
我的代码是:
背景.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if ( changeInfo.status == 'complete' && tab.status == 'complete' && tab.url != undefined ) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {method: "reDraw"}, function(response) {
console.log("Injection ready!");
});
});
}
});
内容.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.method == "reDraw") {
$.get(chrome.extension.getURL('/mytest.html'), function(data) {
$(data).insertAfter('#placeholder-player');
});
}
}
);
chrome.tabs.onUpdated
也会触发 iframe,对于 youtube,有很多 iframe 会触发此事件,除此之外,当你从一个视频转到另一个视频时,youtube 不会重新加载页面。有关 YouTube 问题的更多详细信息,您可以查看以下主题:
- https://bugs.chromium.org/p/chromium/issues/detail?id=165854
- Chrome webNavigation.onComplete 不起作用?
- chrome 扩展 chrome.tabs.onUpdated 运行两次?
So my recommendation would be using chrome.webNavigation
api, and combining webNavigation.onCompleted
with webNavigation.onHistoryStateUpdated
, sample code would look like the following
考虑到您正在检测 YouTube 视频页面,我建议您使用chrome.webNavigation.onHistoryStateUpdated
// To handle youtube video page
chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) {
if(details.frameId === 0) {
// Fires only when details.url === currentTab.url
chrome.tabs.get(details.tabId, function(tab) {
if(tab.url === details.url) {
console.log("onHistoryStateUpdated");
}
});
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)