我对Chrome扩展程序完全不熟悉,但我已经阅读了Google的入门和组合示例。我想构建一个扩展,当它处于活动状态时,它会捕获mydomain.com上的鼠标中键事件,读取URL,修改它并使用新创建的URL启动新选项卡。
据我所知,到目前为止,我需要有一个manifest.json文件和一个my_script.js文件,该文件将在所有mydomain.com页面加载中注入。它是否正确 ?如果是,我应该如何继续下一步,我应该添加到我的清单和javascript文件中以完成给定的任务。一些代码示例将非常感激。
我还在stackoverflow上读了一个couple of answers,如果要使用browserAction
,它只能在扩展页面中使用,所以你不能在内容脚本中使用它。这意味着我必须将我的代码放在后台页面而不是my_script.js中。请告知我该如何处理。
谢谢
工作脚本解决方案是:
$(document).click(function(e) {
var urlToGo = window.location.href;
// middle button
if (e.which == 2) {
urlToGo = "http://google.com";
window.open(urlToGo);
e.preventDefault();
e.stopPropagation();
}
});
答案 0 :(得分:1)
您可以从我的简单Chrome扩展程序内容脚本框架https://github.com/robin-drexler/Simple-Chrome-Extension-Content-Script-Skeleton开始,该框架提供清单和内容脚本,这些脚本将在您访问的每个页面上执行。
现在,您可以继续实施所需的功能。 然后,您可以使用windowow.open打开新的标签/窗口(更简单的方法),也可以使用本机Chrome API打开新标签页。
window.open(在内容脚本中)
$(function() {
$(document).on('click', function(e){
//do some replace magic here
var url = 'http://google.com';
if (e.which === 2) {
window.open(url);
}
});
});
Chrome API的有趣读物
后台页面和内容脚本之间的消息传递。 IIRC您只能在后台页面中使用CHrome Tab API。 http://developer.chrome.com/extensions/messaging.html
Chrome Tab API http://developer.chrome.com/extensions/tabs.html
答案 1 :(得分:0)
你需要让manifest.json声明一个内容脚本,它是将要为每个页面运行的js文件(如果你将属性设置为“all_frames”,则递归到文档中的每个帧) )。
检查此示例manifest.json:
{
"name": "MyExtension",
"version": "0.2",
"manifest_version": 2,
"description": "My description.",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery.js", "my_javascript_to_execute_on_each_frame.js"],
"all_frames": true
}
]
}
使用此清单,您必须提供jquery(可选)和单个js文件以及侦听鼠标单击的代码,更改当前文档的URL并打开新选项卡。这个脚本可能是这样的:
$(document).click(function(e) {
var urlToGo = window.location.href;
// middle button
if (e.which === 2) {
urlToGo = ... // do your url hackery =)
window.open(urlToGo);
e.stopPropagation();
}
});
答案 2 :(得分:0)
正如一点注意事项,中间按钮可能不是一个好主意,因为它是最冗余的,用户最不经常使用,甚至可能在某些设备中丢失,尤其是在触摸屏上。你应该重新考虑你的方法,支持使用第一个鼠标按钮,可以通过你自己提到的浏览器操作按钮有条件地启用或禁用你的消退,或者更好的是 - 页面操作按钮,因为你想要仅适用于特定领域。
至于您感兴趣的代码(对于中间按钮),它没有任何关于扩展的特殊内容,它只是一个常用的JavaScript来处理页面的DOM,其中注入了内容脚本。例如,您可以将处理程序绑定到类似这样的点击:
document.onmousedown = mouseDown;
function mouseDown(e)
{
var midclick;
if (!e) var e = window.event;
if (e.which) midclick = (e.which == 2);
else if (e.button) midclick = (e.button == 4); // MS
if (midclick)
{
var target;
if (e.target) target = e.target;
else if (e.srcElement) target = e.srcElement;
if (target.innerHTML) // do stuff what you need here,
{ // assume get all the content as url
openNewURL(target.innerHTML);
}
}
}
function openNewURL(newurl)
{
chrome.extension.sendMessage({url: newurl}, function(response) {});
}
您的第一个理解是正确的:您需要清单和内容脚本以及背景页。
在后台页面处理传入的请求:
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse)
{
if (request.url)
{
chrome.tabs.create({url: request.url});
}
});