gpt4 book ai didi

javascript - 在 chrome 扩展上下文菜单中获取选择 DOM

转载 作者:行者123 更新时间:2023-11-30 08:01:03 29 4
gpt4 key购买 nike

我尝试通过 Chrome 扩展程序中的 ContextMenu 获取我选择的 DOM。

代码:

chrome.contextMenus.onClicked.addListener(function(info, tab){
// the info.selectionText just the text, don not contains html.
});

chrome.contextMenus.create({
title: "Demo",
contexts: ["selection"],
id: "demo"
});

但是 info.selectionText 不包含 HTML DOM。有没有办法在 Chrome 扩展上下文菜单中获取选择 dom?。请建议。谢谢。

最佳答案

要访问选择,您需要注入(inject) content script进入页面。

在那里,您可以调用 getSelection() 来获取 Selection object并使用其中的范围来提取您需要的 DOM。

// "activeTab" permission is sufficient for this:
chrome.contextMenus.onClicked.addListener(function(info, tab){
chrome.tabs.executeScript(tab.id, {file: "getDOM.js"})
});

getDOM.js:

var selection = document.getSelection();
// extract the information you need
// if needed, return it to the main script with messaging

您可能想看看 Messaging docs .

关于javascript - 在 chrome 扩展上下文菜单中获取选择 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211174/

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