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

来源:互联网 发布:mac怎么截取gif动态图 编辑:程序博客网 时间:2024/06/05 16:00

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'}); });

原创粉丝点击