2016-09-21 82 views
0

Stackoverflow社区,你好。我在此寻求一些帮助,帮助您了解如何使用Google Chrome浏览器扩展程序的消息API将"this"the id of "this"一起发送。Chrome扩展|使用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相对较新,使用file和s使用消息传递API将信息从一个脚本结束到另一个脚本让我感到相当困惑,并希望你们中的一个能够帮助我确定"this"the ID value of this是如何从一个文件发送到另一个文件的。

如果任何人都可以帮助即使在这个具体要求中的最小的,你的帮助将不可思议地赞赏。

回答

1

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

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

第三,你在你的Listener.js,这可能是没有准备好与DOM的工作,我建议将其绑定到的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?如果没有,您需要通过添加了jQuery插件,并在清单注射作为content_script做到这一点:

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

你做出非常正确的观点,我知道它可能看起来与建筑有点奇怪。请原谅我对你的问题的了解,但是一旦点击了具有.cb-enable特定类的元素,它是否会发送要在if语句中使用的“this”id?也感谢你相当快速的回答。 – Fearcustard

+0

是的,我附上的代码 - msg var,在您的script.js中收到的将包含您在popup.html中使用class .cb-enable单击的元素的id。但只有ID,不完整的实体。 – MobDev

+0

你可以在你的script.js中做这样的事情:'if(msg ==“id1”){...}' – MobDev