想写一个支持html转PDF的小工具方便本身平常使用,因而乎查了查资料关于怎么写chrome extension。记录撸代码的过程。javascript
extension主要是四块:manifest.json, content script, background script, popup。manifest.json定义了extension的基本信息、权限、后三者的结构。后三者之间只能经过message通讯,能够理解为在不一样的sandbox中。html
以下manifest定义了permission、content、background、browser_action。能够注意到content_scripts字段是一个数组结构,而background却只能有一个。browser_action能够定制extension的图标和弹出的popup页面内容。java
{
"name": "...",
"version": "1.0",
"description": "...",
"permissions": [
"downloads",
"activeTab",
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"browser_action": {
"default_popup": "index.html",
},
"manifest_version": 2,
"content_security_policy": "script-src 'self' 'sha256-GgRxrVOKNdB4LrRsVPDSbzvfdV4UqglmviH9GoBJ5jk='; object-src 'self'"
}
复制代码
content_scripts是能拿到当前访问的网页元素。也就是script中写个console.log会输出在当前的Chrome deveploment tool上。react
// listener的message
chrome.runtime.onMessage.addListener(function(message, sender,senderResponse){
//...
});
复制代码
background script只能经过background page进行debug。该区域也没有直观UI效果。 git
chrome.browserAction.onClicked.addListener(function(tab){
// send message to tab
chrome.tabs.sendMessage(tab.id, {text: "hello, i'm back"});
})
复制代码
点击extension图标是弹出页面 github
message是不一样区域之间通讯的惟一方式,而且只有content script能够获取当前页面的dom节点。chrome
chrome.runtime.onMessage
chrome.runtime.sendMessage
chrome.tabs.sendMessage
chrome.runtime.onconnect
复制代码
通讯这一块没有深刻,遇到了Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist。试过几种方法发现跟时序有些关系,貌似过早调用runtime会链接失败,没有解决这个问题,后面换了种写法貌似避开了这个问题:( 。后期须要理解一下Live connectjson
chrome.tabs.query({
active: true,
currentWindow: true
}, (tabs) => {
const tab = tabs[0];
chrome.tabs.sendMessage(tab.id, {text: "changeColor"});
});
复制代码
在使用create-react-app脚手架时遇到的几点问题:api
/*global chrome*/
复制代码
{
"scripts": {
"start": "react-scripts start",
"build": "INLINE_RUNTIME_CHUNK=false react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
}
复制代码
主要代码:github react_html2Pdf,目前只完成了粗糙的extension脚手架。数组
参考: