网站首页 > 知识剖析 正文
需求:可能会有在页面加载的时候想执行某个js,例如统计页面的DOM等等。
那么这里就需要用到content_scripts.
在这之前,先放一个类似通用的模版,基本上大部分的扩展程序都可以在上面修改。
manifest.json配置
{
"manifest_version":2,
"app":{
"background":{
"scripts":["background.js"]
}
},
"name":"your extension name",
"version":"1.0",
"default_locale":"en",
"description":"your extension description",
"icons":{
"16":"img/icon16.png",
"48":"img/icon48.png",
"128":"img/icon128.png"
},
"browser_action":{
"default_icon":{
"19":"img/icon19.png",
"38":"img/icon38.png"
},
"default_title":"extension title",
"default_popup":"popup.html"
},
"page_action":{
"default_icon":{
"19":"img/icon19.png",
"38":"img/icon38.png"
},
"default_title":"extension title",
"default_popup":"popup.html"
},
"background":{
"scripts":["background.js"]
},
"content_scripts":[
{
"matches":["http://www.byyui.com/*"],
"css":["mystylesheet.css"],
"js":["jquery.js","myjs.js"]
}
],
"options_page":"option.html",
"permissions":[
"*://www.gstyle.com/*"
],
"web_accessible_resources":[
"img/*.png"
]
}
以上这个基本上能满足大部分的扩展需求,以后在开发,可以在这上面进行删减。不认识没关系,一个一个的来练习。
这一节用到的就是content_scripts.操作用户正在浏览的页面。
通过content_scripts可以指定将哪些脚本文件注入到哪些页面中,用户访问可以,对应的脚本会自动执行,从而对DOM进行操作。
简单说下content_scripts里面的属性:
content_scripts 是一个数组,数组里面是对象,对象中包含的字段有:
- matches
- exclude_matches
- css
- js
- run_at
- all_frames
- include_globs
- exclude_glbos
对应的含义是:
- matches 定义哪些页面会被注入脚本
- exclude_matches 定义哪些页面不会被注入脚本
- css ,js 定义注入的样式和js文件
- run_at 定义了何时注入
- all_frames 定义脚本是否会注入到frame框架中
- include_globs 和 exclude_globs 则是全局URL匹配。最终脚本是否会被注入到哪些页面中是由matches exclude_matches include_globs exclude_globs 的值共同决定。
其中要注意的是:脚本的变量和浏览页面的变量是不通的。
OK,那么我们现在来做一个最简单的控制,在某个url浏览器在控制台打印出我们的字符串。
manifest.json 如下:
{
"manifest_version":2,
"name":"DOM - DEMO",
"version":"1.0",
"description":"操作DOM 练习",
"content_scripts":[
{
"matches":["http://*.byyui.com/"],
"js":["demo.js"]
}
]
}
demo.js
console.log('my extension print log')
由于没有页面,我们只需要这些就足够了。 chrome浏览器加载后,我们浏览 http://www.byyui.com 就会发现控制台已经打印出我们的字符串了。
猜你喜欢
- 2024-11-26 HTML元素语义化,提升网页品质
- 2024-11-26 前端知识杂记(vite&webpack option&composition watch)
- 2024-11-26 那些你从不使用的且有趣的HTML属性
- 2024-11-26 javaScript-第三章
- 2024-11-26 怎么修改WordPress网站divi主题修改中文字体样式CSS?
- 2024-11-26 PDF开发工具Aspose.PDF功能推荐——在.NET中将PDF转换为HTML
- 2024-11-26 TinyMCE 编辑邮件模板 FineUICore
- 2024-11-26 Rust 代码风格 Tips
- 2024-11-26 HTML学习笔记(1)
- 2024-11-26 前端复习html(二)
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)