Chrome扩展上下文菜单:如何在点击菜单项后将div附加到页面 [英] Chrome Extension Context Menu: how to append div to page after clicking menu item

查看:114
本文介绍了Chrome扩展上下文菜单:如何在点击菜单项后将div附加到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打造Chrome扩展程序。目前我已经组合了一个上下文菜单项。当点击上下文菜单项时,它会在后台脚本中触发 itemClicked() context_menu.js

  function itemClicked(info,tab){
alert(clicked);
}

警报触发。我也可以通过 itemClicked()



发送ajax请求,但是我无法附加任何元素到页面(或任何类型的DOM操作)。即使像这样基本的东西也行不通:

  var d = document.createElement('div'); 
d.setAttribute(css,width:100px; height:100px; background-color:red; position:fixed; top:70px; left:30px; z-index:99999999999;);
document.body.appendChild(d);

所以我尝试将相同的代码添加到内容脚本中:

  chrome.contextMenus.onClicked.addListener(函数(OnClickData信息,tabs.Tab选项卡){
//在这里追加输入的代码
});

但它仍然不起作用。我做错了什么?



如何获取上下文菜单以在点击后将内容附加到页面上?



非常感谢!



编辑:这是我的manifest.json(删除了像名称/描述等无关的东西)

  {


权限:[
activeTab,
tabs ,
cookies,
contextMenus
],

background:{
scripts:[context_menu.js]]

browser_action:{
default_icon:icon16.png,
default_css:popup.css,
default_popup :popup.html
},

content_scripts:[
{
matches:[< all_urls>],
js:[vendor / jquery-1.8.2.min.js,config.js,content_script.js]
}
],

web_accessible_resources:[popup.html]

}


解决方案

你可能误解了 后台页面 的概念(和它更年轻,更资源友好和首选的兄弟姐妹: 活动页面 )以及 内容脚本



内容脚本


  • 绑定到特定的网页加载到一个标签中。
  • 生活在一个孤立的世界(JS上下文)中,但可以直接访问网页DOM。
  • 可以与后台页面进行通信(请参阅 消息传递 )。



后台网页




  • 绑定到您的扩展名(有最大值。 1个背景(或事件)页面。)

  • 总是处于背景的某个位置(活动页面不时会打盹,但您可以随时将其唤醒) 。
  • 无法直接访问任何网页。
  • 可以与内容脚本(以及其他视图)进行通信(请参阅 消息传递 )。

  • 可以做很酷的事情(因为它们可以访问很酷的 chrome。* API)






  • chrome.contentMenus API仅适用于后台页面。因此,您必须创建任何上下文菜单并在那里监听 onClicked 事件(在后台页面中)。

    一旦点击了上下文菜单,您可以使用 程序化注入 注入一些代码(或内容脚本)插入到活动标签的网页中。

    以下是演示此方法的示例扩展的源代码。



    manifest.json:

      {
    manifest_version :2,
    name:Test Extension,
    version:0.0,

    background:{
    persistent: false,//< - 让我们将其设为活动页面
    scripts:[background.js]
    },

    permissions:[
    contextMenus,
    activeTab//< - 在这里,足够用于我们的目的
    ]
    }


    $ b background.js:

      / *创建上下文-menu * / 
    chrome.contextMenus.create({
    id:myContextMenu,//< - 必须事件页
    title:Click me,
    上下文:[all]
    });
    $ b $ *注册`onClicked`事件的监听器* /
    chrome.contextMenus.onClicked.addListener(function(info,tab){
    if(tab){
    / *创建要注入的代码* /
    var code = [
    'var d = document.createElement(div);',
    'd.setAttribute(风格,'
    +'背景颜色:红色''
    +'宽度:100px;'
    +'高度:100px;'
    +'position:fixed; '
    +'top:70px;'
    +'left:30px;'
    +'z-index:9999;'
    +');',
    'document.body.appendChild(d);'
    ] .join(\ n);

    / *将代码注入当前标签* /
    chrome.tabs.executeScript(tab.id,{code:code});
    }
    });

    (如果你的注入代码很复杂,注入一个.js文件可能是个好主意。有关 程序化注入 的详细信息。)


    Playing around with building a Chrome extension. At the moment I've put together a context menu item. When the context menu item is clicked, it fires itemClicked() in my background script context_menu.js:

    function itemClicked(info, tab) {
         alert("clicked");
    }
    

    The alert fires. I can also do stuff like sending ajax requests through itemClicked()

    However, I can't append any elements to the page (or DOM manipulation of any sort). Even something as basic as this doesn't work:

      var d = document.createElement('div');
      d.setAttribute("css", "width: 100px; height: 100px; background-color: red; position: fixed; top: 70px; left: 30px; z-index: 99999999999;");
      document.body.appendChild(d); 
    

    So I tried to add the same code to a content script:

    chrome.contextMenus.onClicked.addListener(function(OnClickData info, tabs.Tab tab) {
      //code to append the input here
    });
    

    But it still won't work. What am I doing wrong?

    How can I get the context menu to append something to the page after clicking?

    Thanks so much!

    Edit: here is my manifest.json (removed the irrelevant stuff like name/description...etc)

    {
    
    
      "permissions": [
        "activeTab",        
        "tabs",
        "cookies",
        "contextMenus"
      ],
    
      "background": {
        "scripts": ["context_menu.js"]
      },
      "browser_action": {
        "default_icon": "icon16.png",
        "default_css": "popup.css",
        "default_popup": "popup.html"
      },
    
      "content_scripts": [
        {      
          "matches": ["<all_urls>"],
          "js": ["vendor/jquery-1.8.2.min.js", "config.js", "content_script.js"]   
        }
      ],
    
      "web_accessible_resources": ["popup.html"]
    
    }
    

    解决方案

    You have probably misunderstood the concept of a background page (and its younger, more resource-friendly and preferred sibling: event page) and that of a content script.

    content scripts:

    • Are bound to a specific web-page loaded into a tab.
    • Live in an isolated world (JS context), but have direct access to the web-pages DOM.
    • Can communicate with the background page (see Message Passing).

    background pages:

    • Are bound to your extension (there is max. 1 background (or event) page for each extension).
    • Are always somewhere in the background (event pages "take a nap" from time to time, but you can always wake them up).
    • Do not have direct access to any web-page.
    • Can communicate with the content scripts (and other views) (see Message Passing).
    • Can do cool stuff (because they have access to cool chrome.* APIs).

    The chrome.contentMenus API is available only to a background page. Thus, you have to create any context menu and listen for onClicked events there (in the background page).
    Once a context menu has been clicked, you can use Programmatic Injection to inject some code (or a content script) into the active tab's web-page.

    Below is the source code of a sample extension that demonstrates this method.

    manifest.json:

    {
        "manifest_version": 2,
        "name":    "Test Extension",
        "version": "0.0",
    
        "background": {
            "persistent": false,   // <-- let's make it an event page
            "scripts": ["background.js"]
        },
    
        "permissions": [
            "contextMenus",
            "activeTab"   // <-- here, sufficient for our purpose
        ]
    }
    

    background.js:

    /* Create a context-menu */
    chrome.contextMenus.create({
        id: "myContextMenu",   // <-- mandatory with event-pages
        title: "Click me",
        contexts: ["all"]
    });
    
    /* Register a listener for the `onClicked` event */
    chrome.contextMenus.onClicked.addListener(function(info, tab) {
        if (tab) {
            /* Create the code to be injected */
            var code = [
                'var d = document.createElement("div");',
                'd.setAttribute("style", "'
                    + 'background-color: red; '
                    + 'width: 100px; '
                    + 'height: 100px; '
                    + 'position: fixed; '
                    + 'top: 70px; '
                    + 'left: 30px; '
                    + 'z-index: 9999; '
                    + '");',
                'document.body.appendChild(d);'
            ].join("\n");
    
            /* Inject the code into the current tab */
            chrome.tabs.executeScript(tab.id, { code: code });
        }
    });
    

    (If your injected code is complicated enough, it might be a better idea to inject a .js file. More info on Programmatic Injection.)

    这篇关于Chrome扩展上下文菜单:如何在点击菜单项后将div附加到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆