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

标签 javascript html google-chrome google-chrome-extension

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/

相关文章:

JavaScript 对象数组

javascript - 更改标签内的文本 onclick

html - 如何阻止文本区域在两个不同版本的 chrome 上看起来不同?

html - Canvas 项目无法正确呈现

javascript - 暂停视频不会停止 html5 视频标签中的音频

css - Chrome 瘦身 CSS 网格神秘缺口

javascript - 我如何使用 Google Maps geocoder.getLatLng() 并将其结果存储在数据库中?

javascript - 在 HTML 中调用匿名函数

javascript - Neo4j javascript - Session.run() - 如何在 session 中运行多个查询

html - CSS:在 "hover"标签内制作 "a"标签的 "span",消失了