js 添加chrome右键菜单

本文介绍了一个用于Chrome浏览器的扩展程序开发实例,该扩展程序能够添加右键菜单,并实现页面间的跳转与数据传递功能。文章详细展示了从背景页、内容脚本到主脚本的实现过程,包括HTML、JSON配置及JavaScript代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

135736_rqUr_2007139.png
135757_X0oV_2007139.png

140622_NMAv_2007139.png

1.background.html

<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />
    <title>Hylanda</title>
    <script type="text/javascript" src="\assets\scripts\jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="\assets\scripts\main.js"></script>
</head>
<body>
</body>
</html>

2.manifest.json
{
 "name": "紫藤浏览",
 "manifest_version": 2,
 "version": "0.3",
 "permissions": [
    "http://*/*",
    "https://*/*",
    "contextMenus",
    "tabs",
    "cookies"
  ],
 "content_scripts": [
 {
    "matches": ["http://*/*", "https://*/*"],
    "js": ["assets/scripts/cs.js"],
    "run_at": "document_end"
 }
 ],
 "icons" : {
    "16" : "assets/images/imageinfo-16.png",
    "48" : "assets/images/imageinfo-48.png",
    "128" : "assets/images/imageinfo-128.png"
 },
  "background": {
    "page": "background.html"
  }
}

3.cs.js

function dowork(data){
    console.log(data);
}
function injectjs(content, type){
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    if( type == 'file' ){
        var path = chrome.extension.getURL("assets/scripts/knowledge/"+content);
        script.src = path;
    }else if( type == 'string'){
        script.textContent = content;
    }
    document.documentElement.appendChild(script);
}
document.addEventListener("loginEnd", function(data) {
    chrome.extension.sendMessage({cmd:'login_succ',reshipurl:data.detail});
});
chrome.extension.onRequest.addListener(function(request,sender,sendResponse){
    var res = "";
    if(request.cs_cmd !== null){
        if(request.cs_cmd == "filldata"){    
            strRequest = JSON.stringify(request.cs_data);
            csdata = request.cs_data;
            /*
            csdata.texttitle = d.contents.content.texttitle;
            csdata.shortpic = "";
            csdata.htmltext = d.contents.content.htmltext;
            csdata.abstract = d.contents.content.abstract;
            csdata.pageurl = d.contents.content.pageurl;
            csdata.author = d.contents.content.auth;
            csdata.originalurl = d.contents.content.originalurl;
            csdata.pubdate = d.contents.content.pubdate;
            */
            document.getElementById('title').value = csdata.texttitle;
            //document.getElementById('title').value = csdata.htmltext;
            document.getElementById('author').value = csdata.author;
            tmptext = csdata.htmltext.replace(/&lt;/igm, '<');
            tmptext = tmptext.replace(/&gt;/igm, '>');
            tmptext = tmptext.replace(/&quot;/igm, '"');
            tmptext = tmptext.replace(/&amp;/igm, '&');
            document.getElementById('_m_title').innerHTML = csdata.texttitle;
            document.getElementById('_tempContent').value = tmptext;
            document.getElementById('digest').innerHTML = csdata.abstract;

            /*document.getElementById('title').value = 'lalala';*/
//            injectjs("document.tmpcontent='"+csdata.htmltext+"';",'string');
             injectjs("document.tmpeditor.setContent(document.getElementById('_tempContent').value);",'string');
//            injectjs("document.tmpeditor.setContent('"+tmptext+"');",'string');
        }else if(request.cs_cmd == 'reship_start'){
            injectjs('Prompt.loading.show();','string');
        }else if(request.cs_cmd == 'reship_end'){
            injectjs('Prompt.loading.hide();','string');
        }

    }
    sendResponse(res);
});

4.main.js
 

var tt = (function(){
    var root = this;

    localStorage.website_login = "false";
    //初始化
    root.init = function(){
        //chrome.extension.onRequest.addListener(
        
    };
    //h2x
    root.h2xdata = function(reshipurl,cb){
        var that = this;
        function mh(url,data,callback){
            $.ajax({
                    url :  url,
                    dataType:"jsonp",
                    data : data,
                    beforeSend : function(){

                    },
                    success : function(d){
                        
                        if(typeof callback == "function"){
                            callback(d);
                        }
                        
                    },
                    error : function(){

                    }
            });
        }
        
        function getDataAsyForTabId(url,cb){
            var xhr = new XMLHttpRequest();
            if(xhr==null) return false;
            try{
                xhr.open("GET", url, true);
                xhr.onreadystatechange = function(){
                    if (xhr.readyState == 4){
                        if(xhr.status==200){
                            var data = xhr.responseText;
                            typeof cb==='function' && cb(data);
                            xhr = null;
                        } else {
                            typeof cb==='function' && cb('');
                        }
                    }
                }
                xhr.send();
            }catch(err){
                return false;
            }
            return true;
        }
        var url = 'http://www.zt.com/Home/Detail/index.html?w=' + encodeURIComponent(reshipurl);
        getDataAsyForTabId(url, function(d){
            if(typeof cb == "function"){
                cb(d);
            }
        });
    };
    //右键菜单
    
    root.createMenus = function(){
        var menus = this;
        var contexts = ["page","selection","link","editable","image","video","audio"]; 
        //var contexts = ["page"]; 
        
        document.id = chrome.contextMenus.create({"title": "用紫藤浏览", "contexts":contexts,"onclick": clickMenus});
/*
        function clickMenus(info, tab){
            // 触发转载
            rurl = info.pageUrl;
            root.h2xdata(rurl,function(d){
                //console.log(d);
                root.openEdit(d);
            });
        }
*/        
        function clickMenus(info, tab){
            // 触发转载
            rurl = info.pageUrl;
            root.getCookie(function(strLogin){
                if(localStorage.website_login === "true"){
                    root.reshippage(rurl);
                }else{
                    root.openLogin(rurl, function(tabid){
                    //do nothing
                    });
                }
            });
            return function(info, tab) {
                info.linkUrl;
            };

        }
    };
    root.openEdit = function(cb){
        chrome.tabs.create({url:"http://ziteng.hylanda.com/Home/Detail/index.html",selected:true}, function(tab){
            cb(tab.id);
        })
    }
    root.openLogin = function(reshipurl, cb){
        loginurl = 'http://ziteng.hylanda.com/Home/Detail/index.html';
        loginurl += '?w='+encodeURIComponent(reshipurl);
        chrome.tabs.create({url:loginurl, selected:true}, function(tab){
            cb(tab.id);
        })
    }
    root.getCookie = function(cb){
        objDate = new Date();
        dwTime = objDate.getTime();
        strid = "";
        strname = "";
        bExpiration = true;// true 过期 false 不过期
        chrome.cookies.getAll({domain:"ziteng.hylanda.com"}, function(arrCookie){
            var len = arrCookie.length;
            var i = 0;
            for(i=0; i<len; ++i){
                if(arrCookie[i].name == "manggo_home_uid"){
                    if(arrCookie[i].value !== '0'){
                        exp = arrCookie[i].expirationDate*1000;
                        if(exp >= dwTime){
                            bExpiration = false;
                        }else{
                            bExpiration = true;
                        }
                    }
                    break;
                }
            }
            if(!bExpiration){
                //判断为登录
                localStorage.website_login = "true";
            }else{
                //判断为未登录
                localStorage.website_login = "false";
            }
            typeof cb==='function' && cb(localStorage.website_login);
        });
    }
    root.cslistener = function(){
        chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
            //
            if(request.cmd = 'login_succ'){
                root.reshippage(request.reshipurl);
            }
        });
    };
    
    root.reshippage = function(rurl){
        root.openEdit(function(tabid){
            root.h2xdata(rurl, function(d){
                chrome.tabs.sendRequest(tabid, {cs_cmd:'reship_start'}, function(res){});
                setTimeout(function(){
                    d1=JSON.parse(d);
                    csdata = {};
                    csdata.texttitle = d1.contents.content.texttitle;
                    csdata.shortpic = "";
                    csdata.htmltext = d1.contents.content.htmltext;
                    csdata.abstract = d1.contents.content.abstract;
                    csdata.pageurl = d1.contents.content.pageurl;
                    csdata.texthref = d1.contents.content.pageurl;
                    console.log(d1.contents.content);
                    csdata.author = d1.contents.content.auth;
                    csdata.originalurl = d1.contents.content.originalurl;
                    csdata.pubdate = d1.contents.content.pubdate;
//                        cs_data.originalurl = d1.contents.content.originalurl;
                    chrome.tabs.sendRequest(tabid, {cs_cmd:'filldata',cs_data:csdata}, function(res){});
                    chrome.tabs.sendRequest(tabid, {cs_cmd:'reship_end'}, function(res){});
                }, 5000);
            });
        
        });
    };
    
    
    root.init();
    root.cslistener();
    root.createMenus();
    return root;
})();

 

 

注: 为chrome浏览器添加扩展程序,添加右键菜单,链接到其他页面

转载于:https://my.oschina.net/guoxin2014/blog/808317

### 实现Chrome扩展程序中的自定义右键菜单功能 为了在Chrome浏览器中创建一个能够向选中文本添加自定义右键菜单项的扩展,开发者可以利用`contextMenus` API来完成这一目标[^1]。 #### 创建Manifest文件 首先,在项目的根目录下建立名为`manifest.json`的配置文件。此文件用于声明扩展的基本信息及其权限需求: ```json { "manifest_version": 3, "name": "Custom Context Menu", "version": "1.0", "permissions": [ "contextMenus" ], "background": { "service_worker": "background.js" } } ``` #### 编写Background脚本 接着编写背景页面逻辑,即`background.js`,用来监听用户的操作并响应特定事件: ```javascript // 当用户点击上下文菜单时触发该函数 function onContextMenuClick(info, tab) { console.log(`Selected text: ${info.selectionText}`); } // 向已有的默认右键菜单里增加新的选项 chrome.contextMenus.create({ id: 'customMenu', title: 'Do Something with Selected Text', contexts: ['selection'] // 只有当存在选区的时候才会显示这个条目 }); // 注册回调处理程序 chrome.contextMenus.onClicked.addListener(onContextMenuClick); ``` 上述代码片段展示了如何注册一个新的上下文菜单命令,并指定其仅适用于被选取的文字区域;同时设置了点击后的行为——这里简单打印出了所选文字到控制台日志中。 通过这种方式,便可以在Chrome浏览器内成功集成针对选定文本的个性化快捷方式支持了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值