用js获取网页DOM(例:input标签的ID)的chrome插件

[html]  view plain  copy
  1. </pre><p>在JavaScript中有多钟获取DOM元素的方法,常见的有getElementById、getElementsByName、getElementsByTagName、getElementsByClassName,分别是通过id、name、标签名和类名获取元素,注意只有第一个是Element,其他三个都是Elements,因为HTML中元素名必须唯一,其他则不必。下面就以获取网页input标签的ID为例:</p><p>1、</p><p>manifest.json:</p><p></p><pre name="code" class="html">{  
  2.     "manifest_version":2,  
  3.     "version":"1.0",  
  4.     "name":"getid",  
  5.     "description":"get elements'id",  
  6.     "icons":{  
  7.         "16":"images/icon16.png"  
  8.     },  
  9.     "content_scripts":[  
  10.         {  
  11.          "matches":["*://*/*"],  
  12.          "js":["js/content.js"]  
  13.          }  
  14.     ]  
  15. }  

conten.js:

[html]  view plain  copy
  1. window.onload = function(){  
  2.     var list=document.getElementsByTagName("input");  
  3.     var strData;  
  4.     for(var i=0;i<list.length && list[i];i++)  
  5.     {  
  6.         if(list[i].type == "text"&&list[i].id != "subEmail")  
  7.         {  
  8.             strData=list[i];  
  9.             alert(strData.id);  
  10.         }  
  11.     }  
  12. }  

加载插件成功后,重新载入页面,即可看到弹框显示的每个input的ID。

2、要是想通过页面间的通信来实现上面的功能:函数如下:

manifest.json:

[plain]  view plain  copy
  1. {  
  2.     "manifest_version":2,  
  3.     "version":"1.0",  
  4.     "name":"getid",  
  5.     "description":"get elements'id",  
  6.     "icons":{  
  7.         "16":"images/icon16.png"  
  8.     },  
  9.     "background":{  
  10.         "scripts":[  
  11.            "js/background.js"  
  12.         ]  
  13.     },  
  14.     "content_scripts":[  
  15.         {  
  16.          "matches":["*://*/*"],  
  17.          "js":["js/content.js"]  
  18.          }  
  19.     ]  
  20. }  

background.js:

[javascript]  view plain  copy
  1. /** 
  2.  * Created by Administrator on 15-1-4. 
  3.  */  
  4. chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){  
  5.     alert("ID都有"+message);  
  6.     });  

content.js:

[javascript]  view plain  copy
  1. /** 
  2.  * Created by Administrator on 15-1-4. 
  3.  */  
  4. window.onload = function(){  
  5.     var list=document.getElementsByTagName("input");  
  6.     var strData;  
  7.     for(var i=0;i<list.length && list[i];i++)  
  8.     {  
  9.         if(list[i].type == "text"&&list[i].id != "subEmail")  
  10.         {  
  11.             strData=list[i];  
  12.             chrome.runtime.sendMessage(strData.id);  
  13.         }  
  14.     }  
  15.   
  16. }  

猜你喜欢

转载自blog.csdn.net/awj321000/article/details/79067376
今日推荐