【问题标题】:How to modify Greasemonkey script to be compatible with chrome?如何修改 Greasemonkey 脚本以与 chrome 兼容?
【发布时间】:2011-11-21 21:58:45
【问题描述】:

从之前的SO post 我发现为了让 Greasemonkey 脚本与 Chrome 兼容,我们必须为 jQuery http://erikvold.com/blog/index.cfm/2010/6/14/using-jquery-with-a-user-script 创建脚本元素

如果我当前在 Firefox 中运行良好的用户脚本如下所示。我应该如何修改它以包含上述方法并仍然在 onload 时调用该函数?在之前的帖子中建议的解决方案中,我应该将当前代码放在哪里?

// ==UserScript==
// @name           Google+
// @version        1.1
//
// 
// @include        http://plus.google.com/*
// @include        https://plus.google.com/*
//
// @require        https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js


$(function()
   {

   $(window).bind('load', function()
   {
           console.log("Hi Condition is very bad!")

           $('<div id="vdiv"></div>').prependTo('#contentPane');
           $('<img>',
           {
           src: 'http://icons.iconarchive.com/icons/aha-soft/security/16/key-icon.png',
           alt: 'Key',
           title:'Key',
           click: function(){
           alert($(this).attr('title'));
           var vtext = jQuery('div.f-ba-mg iframe').contents().find('body').text().trim();
           alert(vtext);
           }
           })
           .css({
           cursor: 'pointer',
           border: '1px solid black',
           backgroundColor: 'white'
           })
           .appendTo('#vdiv');
   });
   });

【问题讨论】:

    标签: jquery google-chrome greasemonkey


    【解决方案1】:

    Ehm,您可以确定脚本在 ondomready-event 之后执行,这是greasemonkey 的正常执行时间(chrome 提供了更早的执行时间,但这只是一个特殊选项)。所以没有必要在onload时运行它。所以你实际上可以把它放在任何地方,只要你事先加载了 jQuery。

    Erik 的解决方案可以通过创建 1 个 init-function(通常在 .ready() 处运行),并使用 addJquery(init-function);

    顺便说一句,我包含 jQuery 的方法是将它添加到脚本本身中,否则它必须为每个页面加载(这会减慢速度),所以我在脚本和其他一些解决方案中有一个 jQuery 的缩小版本,见http://userscripts.org/scripts/review/52341 (顺便说一句,我是作为维护者进来的,代码远非完美)。

    那里的解决方案:

    1.) 在 jQuery 之上有一些注释行,然后是 jQuery 1.4.4 的改编和修改版本(因为greasemonkey 环境和普通文档范围之间存在细微差别)。

    2.) 就在这些行之上,我正在使用 localStorage 在 Chrome 上重新创建油脂猴的一些功能。

    3.)greasemonkey 中的 unsafeWindow 大约等于 chrome 中的 window,但仅适用于浏览器本身提供的功能(其他功能被 chrome 阻止,因为它们不安全)。没有使用很多,只有 unsafeWindow.console.log() 和一些不太重要的东西 afaik。

    但是对于你的情况,erik 的方法也可以:

    $(function(){
      $(window).bind('load', function(){
        ...
      });
    });
    

    addJquery(function() {
      ...
    });
    

    【讨论】:

    • 感谢您的回答。能否请您简要介绍一下代码?
    • 我猜想的太多了,但我添加了一些行。
    猜你喜欢
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多