gpt4 book ai didi

jquery - 如何在这个 chrome 扩展文件中包含 jQuery?

转载 作者:行者123 更新时间:2023-12-01 04:03:27 26 4
gpt4 key购买 nike

我正在学习编写 chrome 扩展,并且希望将 jQuery 包含在我正在使用的文件中。我已经在这里阅读了很多答案,但我仍然不明白。我可能会以错误的方式处理这件事,所以请告诉我。在我的浏览器弹出窗口 popup.html 中,我让用户单击一个按钮,然后该按钮调用我的 content.js 文件,目前这只是一个简单的警报,但最终我打算使用它来操作页面上的 DOM扩展名用于.我想附加 jQuery 库的本地保存副本,以便我可以使用 jQuery 编写 DOM 操作代码。我已尝试将其添加为我的背景文件,并且也类似地添加到我的 content_script 部分中,但它似乎仍然无法加载。这是我的代码

list .json

{
"manifest_version": 2,

"name": "Test",
"description": "Test",
"version": "1.0",

"permissions": [
"tabs", "<all_urls>"
],

"browser_action": {
"default_icon": "wfhm.png",
"default_popup": "popup.html"
},

"icons": {
"128": "wfhm128.png"
},

"background": {
"scripts": ["jquery.js"]
}
}

popup.html

<!DOCTYPE html>
<html>
<body style="width: 300px">
<h2>test</h2>
<input type='text' placeholder='Search by name..'/>
<button id="btnSearch">Search</button>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

popup.js

function search() {
chrome.tabs.executeScript({
file: 'content.js'
});
}

document.getElementById('btnSearch').addEventListener('click', search);

和 content.js

$(function(){
alert('hi');
$('body').css('background-color', 'yellow');
});

最佳答案

后台脚本位于与弹出脚本(以及内容脚本)不同的环境中。这意味着您加载的 jQuery 不会被看到。相反,您需要使用 popup.js 来执行 jQuery,然后使用回调来执行您的内容脚本:

popup.js:

function search() {
chrome.tabs.executeScript({file: 'jquery.js'},function() {
chrome.tabs.executeScript({file: 'content.js'});
});
}

document.getElementById('btnSearch').addEventListener('click', search);

由于该选项卡已经加载,因此您无需担心内容脚本中的 $(function())。您只需运行您的脚本即可。

关于jquery - 如何在这个 chrome 扩展文件中包含 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35297927/

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