ffmmx's Blog

Happy coding

CHROME插件 “复制选中的链接地址”

    昨日本来在人人影视上面下载美剧,结果那部电视剧太多集了。CHROME下那个复制全部不能用。只好自己写一个。

代码如下:

注册文件 manifest.json

 

{
  "name": "复制选中的链接地址",
  "description": "复制选中的链接地址到剪贴板中(电驴,离线什么的)",
  "version": "0.1",
  "permissions": ["contextMenus","tabs","https://*/*","http://*/*"],
  "background_page": "background.html"
}

实现选中链接文件(之前对CHROME也没有什么了解,临时从chrome API那里下载的一个例子,文件名忘改了) sample.js

 

var selection = window.getSelection();
if(selection.rangeCount > 0)
{
	var range = selection.getRangeAt(0);
	
	var div = document.createElement('div');
	//把复制的内容放入div中,转化为DOM结构
	div.appendChild(range.cloneContents());

	var contents = "";
	//获取div里面的,链接元素
	var aucher_list = div.getElementsByTagName("a");
	
	for (var i = 0; i < aucher_list.length; i++) {
		contents += "\n" + aucher_list[i].href;
	}

	contents = contents.substring(1);
	//向background发送ED2K链接
	chrome.extension.sendRequest({text:contents});
}

background.js

 

<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8">
	
		<title>Background</title>
		<script type="text/javascript" charset="utf-8">
			chrome.extension.onRequest.addListener(function (msg, sender, sendResponse) {

					var textarea = document.getElementById("lnktext");
					
					textarea.value = msg.text;					
					textarea.select();
					document.execCommand("copy", false, null);

					sendResponse({});
					}
					);	


			function copylinkbyselected(info,tab){
				
				chrome.tabs.executeScript(null, { "file" : "sample.js", "allFrames" : true } );
			}

chrome.contextMenus.create(
		{
		"title": "copy link by selected",
		"contexts":["selection"],
		"type":"normal",
		"onclick": copylinkbyselected
		});	
		</script>
	</head>
	<body>
		<textarea id="lnktext" rows="8" cols="40"></textarea>
	</body>
</html>