您的位置:首页 > 其它

chrome插件开发(二) 入门篇(content script )

2013-02-24 19:03 148 查看
1: content scripts是page action将注入到特定页面中的脚本

chrome插件中的 content script 是运行在一个被称为isolated
world 的运行环境里,和页面上的脚本互不干扰,因为不在一个运行环境里,所以也无法调用页面上脚本定义的方法了,当然google也给出了解决方法:http://code.google.com/chrome/extensions/content_scripts.html

看一下代码 content_scripts中引用的js将会在匹配matches的页面中被执行

run_at有document_start | idel | end 三个值可选

{  
  	"name": "coffee",
  	"manifest_version":2,
	"version": "1.0",  
	"description": "coffee test",  
	"browser_action": {  
	   "default_icon": "icon.png" ,
	   "default_title": "My Task List",
    	"default_popup": "popup.html"
	 },
	 "background": {
	    "page": "background.html"
	  },
	 "content_scripts": [{
	     "matches": ["http://*/*","https://*/*"], 
	     "js": ["js/jquery-1.9.1.min.js", "js/test.js"], 
	     "run_at": "document_start",
	     "all_frames": true 
	}],
  	"permissions": [   
   	 "tabs", "http://*/*","https://*/*"  
  	]   
}

test.js

每打开一个tab页,访问matches指定的url 在document加载完成后 ,会弹出alert

alert('hello')

注意:content script有限制:即:js文件中只能使用被其他页面或者content scripts定义的变量或方法

Use variables or functions defined by web pages or by other content scripts

另外:content_script也可以采用如下方式添加

background.html

chrome.browserAction.onClicked.addListener(function(tab) {
     chrome.tabs.executeScript(tab.id, {file: 'jquery.min.js'});
     chrome.tabs.executeScript(tab.id, {file: 'content.js'});
 });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: