gpt4 book ai didi

javascript - Chrome 扩展获取 DOM 文本并在单击按钮时将其显示在 popup.html 中

转载 作者:行者123 更新时间:2023-12-02 14:52:51 29 4
gpt4 key购买 nike

SO 和其他地方有大量关于此的信息,但我无法让它工作!

我有这个 popup.html:

<html>
<head>
<title>My popup that should display the DOM</title>
<script src="popup.js"></script>
</head>
<body>
<button id="btn">Click!</button>
<input type="text" id="info">
</body>
</html>

我的manifest.json:

{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",

"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*" ],
"js": ["jquery-2.2.1.min.js","content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs"]
}

背景.js:

function doStuffWithDOM(infoHtmlText) {
alert("I received the following DOM content:\n" + infoHtmlText);
chrome.extension.getBackgroundPage().info = infoHtmlText;
}


chrome.tabs.onUpdated.addListener(function(id,changeInfo,tab){
if(changeInfo.status=='complete'){ //To send message after the webpage has loaded
chrome.tabs.sendMessage(tab.id, { status: "ok" },function(response){
infoHtmlText = $("#domElement").text();
doStuffWithDOM(infoHtmlText);
});
}
})

内容.js:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
/* If the received message has the expected format... */
if (msg.status && (msg.status == "ok")) {
/* Call the specified callback, passing
the web-pages DOM content as argument */
sendResponse("something?");
}
});

是否有一个简单的示例,您可以单击弹出窗口中的按钮并从 DOM 获取内容并将其显示在弹出窗口中?

最佳答案

这是基于您的代码的示例代码:

popup.js

function hello() {
var name = document.getElementById('info').value;
alert("Hello " +name);
}

document.getElementById('btn').addEventListener('click', hello);

popup.html

<html>
<head>
<title>My popup that should display the DOM</title>

</head>
<body>
<button id="btn">Click!</button>
<input type="text" id="info">
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

list .json

{
"manifest_version": 2,
"name": "Get HTML example w/ popup",
"version": "0.0",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "Get HTML example",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}

background.js :留空(不确定这一点,因为我是 chrome 开发的新手),但它正在工作。

我从这个SO question得到了答案,如果您直接使用内联 header ,您将遇到此错误消息:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

关于javascript - Chrome 扩展获取 DOM 文本并在单击按钮时将其显示在 popup.html 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047322/

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