Chrome扩展程序开发示例

发布于:2024-12-09 ⋅ 阅读:(143) ⋅ 点赞:(0)

项目文件夹内文件如下:

manifest.json文件内容:

{
  "manifest_version": 3,
  "name": "我的法宝",
  "description": "我的有魔法的宝贝",
  "version": "1.0",
  
  "icons": {
    "16": "images/icon.png",
    "32": "images/icon.png",
    "48": "images/icon.png",
    "128": "images/icon.png"
  },
  
  "action": {
    "default_popup": "popup.html",
    "default_icon": "images/icon.png"
  },
  
  "content_scripts": [
    {
      "js": ["content.js"],
      "matches": [
        "https://*/*",
        "http://*/*"
      ]
    }
  ],
  
  "background": {
    "service_worker": "background.js"
  },
  
  "permissions": ["activeTab","scripting","contextMenus"]
  
}

background.js文件内容:

console.log("background script is running");

//创建右键菜单
chrome.runtime.onInstalled.addListener(async () => {  
	chrome.contextMenus.create({
		id: "YoudaoDictionarySearch",
		title: '英汉词典查词:“%s”',  //%s是页面中选中的文本
		type: 'normal',
		contexts: ['selection']
	});
});

//当菜单选项被点击时
chrome.contextMenus.onClicked.addListener((item, tab) => {
	const word=item.selectionText;
	const urlStr='https://www.youdao.com/result?lang=en&word=' + encodeURI(word);
	chrome.tabs.create({url: urlStr}); //创建新标签页
});

popup.html文件内容:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <title>我的法宝</title>
</head>
<body>
	<!--点击浏览器插件图标时会弹出的内容-->
    <h1 style="color:red;width:200px;">我的法宝</h1>
	<p>我的有魔法的宝贝</p>
</body>
</html>

content.js文件内容:

//注入网页内容的脚本
console.log("content js is running");

//此变量用于存储所选中的文字
let selectedText="";

//将选择到的页面内文字存入变量selectedText
document.addEventListener("selectionchange", () => {
	const selection = window.getSelection();
	if (selection.toString()) {
		selectedText = selection.toString();
	}
});

//鼠标左键按下后
document.addEventListener("mousedown", () => {
	selectedText="";
});


//鼠标左键弹起后
document.addEventListener("mouseup", () => {
	if(selectedText!=""){
		console.log(selectedText);
	}else{
		console.log("没有选择任何文本");	
	}  
});









网站公告

今日签到

点亮在社区的每一天
去签到