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

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

问题描述

尝试构建 Chrome 扩展程序.目前我已经组合了一个上下文菜单项.单击上下文菜单项时,它会在我的后台脚本 context_menu.js 中触发 itemClicked():

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");
}

警报触发.我还可以做一些事情,比如通过 itemClicked()

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

但是,我无法将任何元素附加到页面(或任何类型的 DOM 操作).即使像这样基本的东西也不起作用:

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?

非常感谢!

这是我的 manifest.json(删除了不相关的内容,如名称/描述...等)

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.

内容脚本:

  • 绑定到加载到选项卡中的特定网页.
  • 生活在一个孤立的世界(JS 上下文),但可以直接访问网页 DOM.
  • 可以和后台页面通信(见消息传递强>).

背景页面:

  • 绑定到您的扩展程序(每个扩展程序最多有 1 个背景(或事件)页面).
  • 总是在后台某处(活动页面不时打盹",但您可以随时唤醒它们).
  • 不能直接访问任何网页.
  • 可以与内容脚本(和其他视图)通信(参见消息传递).
  • 可以做很酷的事情(因为他们可以访问很酷的 chrome.* API).
  • 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).

chrome.contentMenus API 仅可用于后台页面.因此,您必须创建任何上下文菜单并在那里(在后台页面中)监听 onClicked 事件.
单击上下文菜单后,您可以使用程序化注入 将一些代码(或内容脚本)注入到活动标签的网页中.

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.

ma​​nifest.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("
");

        /* Inject the code into the current tab */
        chrome.tabs.executeScript(tab.id, { code: code });
    }
});

(如果您注入的代码足够复杂,最好注入 .js 文件.有关 程序化注入.)

(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天全站免登陆