如果我只有后台脚本,如何检索已执行上下文菜单的元素?

时间:2015-12-22 14:12:02

标签: javascript dom google-chrome-extension contextmenu vk

它似乎与那个问题类似How to retrieve the element where a contextmenu has been executed 但我无法从中得到任何结果,请帮助我。

 var clickedEl;
document.addEventListener("mousedown", function(event){
        //right click
        if(event.button == 2) { 
            clickedEl = event.target;
        }
        }, true);
var imageSourceUrl;
function getClickHandler() {
    "use strict";

    return function (info, tab) {

 if(tab.url.indexOf('https://vk.com') > -1){
        if(clickedEl.parentNode.href.indexOf('photo') > -1){
        var photoalbumid = clickedEl.parentNode.href.substring(clickedEl.parentNode.href.lastIndexOf("o")+1);

            var getphoto = new XMLHttpRequest();

            getphoto.open('GET', 'https://api.vk.com/method/photos.getById?photos=' + photoalbumid);

            getphoto.onload = function () {

            var answer = JSON.parse(getphoto.response);

            if (answer.response[0].src_big === undefined) {
                thereIsAnError('hueta s polucheniem url img', answer, imageUrl);
                return;
            }
            imageSourceUrl =  decodeURIComponent(answer.response[0].src_big);                                           

            }                                    

            getphoto.send();
    }
}
if(imageSourceUrl === undefined) imageSourceUrl  = info.srcUrl;

           var imageUploadHelperUrl = 'upload.html#',
            vkCLientId           = '128593',
            vkRequestedScopes    = 'docs,offline,groups,stats,photos',
            vkAuthenticationUrl  = 'https://oauth.vk.com/authorize?client_id=' + vkCLientId + '&scope=' + vkRequestedScopes + '&redirect_uri=http%3A%2F%2Foauth.vk.com%2Fblank.html&display=page&response_type=token';

        chrome.storage.local.get({'vkaccess_token': {}}, function (items) {

            if (items.vkaccess_token.length === undefined) {
                chrome.tabs.create({url: vkAuthenticationUrl, active:false}, function (tab) {
                    chrome.tabs.onUpdated.addListener(listenerHandler(tab.id, imageSourceUrl));
                });

                return;
            }

            imageUploadHelperUrl += imageSourceUrl + '&' + items.vkaccess_token;

            chrome.tabs.create({url: imageUploadHelperUrl, active:false}); 
        });
    };
}

 * Handler of chrome context menu creation process -creates a new item in the context menu
 */
chrome.contextMenus.create({
    "title": "Rehost on vk.com",
    "type": "normal",
    "contexts": ["image"],
    "onclick": getClickHandler()
});

chrome说" contextMenus的事件处理程序出错:TypeError:无法读取属性' parentNode'未定义的     at" if(clickedEl.parentNode.href.indexOf(' photo')" line .... 如何在getClickHandler()中访问更改后的clickedEl对吧?

        //background 
var imageSourceUrl;
function getClickHandler() {
    "use strict";

    return function (info, tab) { 
        if(tab.url.indexOf('https://vk.com') > -1){
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {imghref : "gimmemore"}, function(response) {
                    imageSourceUrl = response.imaged;
                    console.log(response.imaged);
                });
            });
        }
        else{imageSourceUrl=info.srcUrl;}
        var imageUploadHelperUrl = 'upload.html#',
            vkCLientId           = '5118087',
            vkRequestedScopes    = 'docs,offline,groups,stats,photos',
            vkAuthenticationUrl  = 'https://oauth.vk.com/authorize?client_id=' + vkCLientId + '&scope=' + vkRequestedScopes + '&redirect_uri=http%3A%2F%2Foauth.vk.com%2Fblank.html&display=page&response_type=token';

        chrome.storage.local.get({'vkaccess_token': {}}, function (items) {

            if (items.vkaccess_token.length === undefined) {
                chrome.tabs.create({url: vkAuthenticationUrl, active:false}, function (tab) {
                    chrome.tabs.onUpdated.addListener(listenerHandler(tab.id, imageSourceUrl));
                });

                return;
            }

            imageUploadHelperUrl += imageSourceUrl + '&' + items.vkaccess_token;

            chrome.tabs.create({url: imageUploadHelperUrl, active:false}); 
        });
    };
}


    //content script
var clickedEl = null;
var photoalbumid = null;
document.addEventListener("mousedown", function(event){
       //right click
        if(event.button == 2) { 
            clickedEl = event.target;
            if(clickedEl.parentNode.href.indexOf('photo') > -1){
                photoalbumid = clickedEl.parentNode.href.substring(clickedEl.parentNode.href.lastIndexOf("o")+1);
                if (photoalbumid.indexOf('?') > -1) {
                    photoalbumid = photoalbumid.slice(0, photoalbumid.indexOf('?'));
                }
            }
            console.log(photoalbumid);
        }
        }, true);
                var getphoto = new XMLHttpRequest();

                getphoto.open('GET', 'https://api.vk.com/method/photos.getById?photos=' + photoalbumid);

                getphoto.onload = function () {

                var answer = JSON.parse(getphoto.response);

                if (answer.response[0].src_big === undefined) {
                thereIsAnError('hueta s polucheniem url img', answer, imageUrl);
                }
                imageSourceUrl =  decodeURIComponent(answer.response[0].src_big);                                           
                }                                    
                getphoto.send();

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request.imghref == "gimmemore") {
        sendResponse({imaged : imageSourceUrl });
    }
});

重新阅读后的改动^

1 个答案:

答案 0 :(得分:0)

您错过了原始答案中的部分,其中的注释解释了代码如何在扩展部分之间分割:

//content script
/* ... */

//background
/* ... */

您需要(重新)阅读Architecture Overview,以便更好地了解Chrome扩展程序的结构。

这里发生的事情是,click事件实际上从未在您的后台发生 - 它发生在实际的页面中,而这就是您可以使用内容脚本捕获它的地方。

但是内容脚本不能作为上下文菜单事件的监听器。你需要背景。所以,这里的(必需的)逻辑是:

  1. 在页面中,单击侦听器准备信息。
  2. 上下文菜单点击发生,后台事件监听器触发。
  3. 后台脚本从内容脚本请求信息。
  4. 内容脚本接收请求,回复信息。
  5. 后台脚本接收回复,处理数据。
  6. 考虑到这一点,请阅读Overview(这次全部),然后再次the original question