gpt4 book ai didi

javascript - Chrome 扩展 |使用类似 Chrome API 的消息发送 "this"和 "this"id 值

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

Stackoverflow 社区,你好。我在此寻求一些帮助,以了解如何使用 Google Chrome 扩展程序的消息 API 发送 “this” 以及 “this”的 id

使用的相关html代码(popup.html)

<p class="field switch bpos">
<label class="cb-enable" id="id1"><span>yes</span></label>
<label class="cb-disable selected"><span>no</span></label>
<input type="checkbox" id="checkbox" class="checkbox">
</p>

Listener.js(外部脚本)(放置在 popup.html 的脚本标签内)

$( ".cb-enable" ).click(function() {
chrome.tabs.executeScript(null, {file:"script.js"});
});

Script.js(从 {file:"script.js"} 运行)

function check(){
if ( $( this ).is('#id1')) {function1(); }
else if ( $( this ).is('#id2')) {function2(); }
else{alert("id not found");}
}
check();

对于 chrome 扩展 API 来说相对较新,文件的使用以及使用消息传递 API 将信息从一个脚本发送到另一个脚本让我相当困惑,我希望你们中的一个人可以帮助我一点"this" 以及 this 的 ID 值 已从一个文件发送到另一个文件。

如果有人能提供哪怕是最轻微的帮助,我们将非常感谢您的帮助。

最佳答案

首先,您必须记住,popup.html 的 DOM 树和可从注入(inject)的 script.js 访问的 DOM 树是不同的。因此,如果您将 jQuery 事件传递给 script.js,它将无法正常工作。相反,您可以将目标 id 传递给 script.js。

其次,为什么每次点击都要将 script.js 注入(inject)到页面中?你可以做一次。然后向页面发送消息。

第三,你在Listener.js中使用DOM,它可能还没有准备好,我建议将它绑定(bind)到document.ready:

可能是这样的:

Listener.js:

$(document).ready(function(){
chrome.tabs.executeScript(null, {file:"script.js"});
$( ".cb-enable" ).click(function(evt) {
target=$(this).attr("id")
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, target, function(response) {
});
});
});
});

script.js:

if(!window.init)
{
window.init=true
chrome.runtime.onMessage.addListener(function(msg){
//do something with msg contains id of clicked button
});
}

第四,你在 script.js 中使用了 jQuery,你是否将它作为 content_script 注入(inject)?如果没有,您需要通过将 jquery 添加到您的插件并将其作为 content_script 注入(inject) list 中来实现:

  ...
"content_scripts": [
{
"js": [
"jquery.js"
],
"matches": [
"http://*/*","https://*/*"
]
}
],
...

关于javascript - Chrome 扩展 |使用类似 Chrome API 的消息发送 "this"和 "this"id 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39627248/

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