chrome扩展程序中的选项卡更改时的页面内容

尼克希尔

background.js

var htmlcontent = null;

chrome.tabs.onUpdated.addListener(function() {
onWindowLoad();
alert(htmlcontent);
});

chrome.tabs.onHighlighted.addListener(function(){
onWindowLoad();
alert(htmlcontent);
});

function onWindowLoad() {
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.extension.lastError) {
htmlcontent = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}

chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
htmlcontent = request.source;
}
});

getPagesSource.js

function DOMtoString(document_root) {
return document.body.innerText ;
}

chrome.extension.sendMessage({
action: "getSource",
source: DOMtoString(document)
});

我正在开发chrome扩展程序。我可以在重新加载时获取当前窗口的正文内容,但是当我更改标签时却无法获取内容。前一个标签的内容将被保存。我使用了错误的API吗?或当我在Chrome中更改标签时,如何触发onUpdate功能?

尼克希尔

终于找到了。

我正在chrome.tabs.onHighlighted.addListener(function()中打印html内容。那一刻,我仍然没有值。

htmlcontent值将仅在chrome.extension.onMessage.addListener(function()处设置)。

因此,如果您尝试打印htmlcontent,您仍将拥有上一个选项卡的内容。

所以流程是

chrome.tabs.onUpdated.addListener(function() {
onWindowLoad();
});

function onWindowLoad() {
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
if (chrome.extension.lastError) {
htmlcontent = 'There was an error injecting script : \n' +     chrome.extension.lastError.message;
}
});
}

chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
htmlcontent = request.source;
//call whatever function from here on so that htmlcontent will have the selected tab's content.
}
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Chrome扩展程序仅在当前选项卡中更改用户代理

Chrome扩展程序-executeScript不在活动选项卡中

在BottomNavigationBar上的选项卡更改时禁用重建页面

Flutter:BottomNavigationBar在选项卡更改时重建页面

在选项卡更改时切换内容

纯CSS选项卡-防止在选项卡更改时滚动到页面顶部

如何在选择更改时更新vaadin选项卡中的内容?

Chrome扩展程序:获取活动选项卡的源代码

Chrome扩展程序:Javascript注入到活动选项卡

Chrome扩展程序中的所有选项卡中设置切换开关状态

在选项卡更改时反应导航

如何使用JavaScript在Chrome扩展程序中获取当前选项卡的URL

Chrome 扩展程序 - 在当前选项卡的 popup.html 中激活脚本

无法从我的 chrome 扩展程序的选项卡中获取选定的文本/突出显示的文本

Chrome 扩展程序化 CSS 注入到活动选项卡中的错误

如何将 JavaScript 发送到 Chrome 扩展程序中的特定选项卡?

单击扩展程序图标时,在新选项卡中打开扩展程序的options.html页面

如何防止页面在页面索引更改时丢失选项卡选择?

仅在Firefox / Chrome扩展程序的一个选项卡中禁用/启用javascript(使用Web扩展程序)

从 Chrome 选项卡中删除/禁用内容脚本

在Gitlab登录页面中更改选项卡名称

从Kivy中的按钮更改选项卡的内容

选项卡索引更改时,mat-tab-group滚动到页面顶部

阻止在引导程序3中显示选项卡内容?

Chrome扩展程序-找出扩展程序选项卡是否打开

选项卡以外的 Xamarin 选项卡式页面内容

Chrome扩展程序:webRequest重定向到现有选项卡,而无需打开新选项卡

更改角度组件中的活动引导程序选项卡

如何在Chrome扩展程序中的后台消息侦听器中检索活动选项卡?