javascript - 如何在注入(inject)代码中使用 GM_xmlhttpRequest?

标签 javascript google-chrome-extension greasemonkey userscripts

我正在编写一个注入(inject)网页的用户脚本。该脚本从网络服务器读取一些数据,我想将消息发送到监听应用程序以对数据使用react。

现在,我所做的只是尝试向我的监听应用程序发送一个字符串命令,看看我是否可以读取它。我的代码在注入(inject)之前工作,但之后我得到一个“ undefined reference 错误”。

我怀疑这与"Greasemonkey access violation"有关.但是,我一直无法找到有效的解决方案。我在 Chrome 中开发。

这是我无法开始工作的代码部分。

GM_xmlhttpRequest({
   method: "POST", 
   url: "http://localhost:7777", 
   data: "testing123",
   headers:  {
         "Content-Type": "application/x-www-form-urlencoded"
             },
   onload: function(response) 
   {
      if (response.responseText.indexOf("TEST") > -1) 
      {
         console.log("Response confirmed..."); 
      }
   }
}); 

我对脚本编写还很陌生,所以我可能遗漏了一些明显的东西。我如何让它在注入(inject)的代码中工作?

最佳答案

GM_ 函数在注入(inject)代码中不起作用,因为注入(inject)代码在目标页面的范围内运行。如果他们确实在那里工作,那么不道德的网站也可以使用 GM_ 功能——做不可言喻的邪恶。

解决方案,最可取的是:

  1. 不要注入(inject)代码。很多时候,它真的没有必要,而且总是使事情复杂化。仅在绝对肯定需要使用目标页面加载的一些 javascript 时才注入(inject)代码。

    对于像 jQuery 这样的库,使用 @require 指令 (Firefox) 或粘贴库代码或使用 a custom manifest.json file 可以获得更好的性能。包含它(Chrome)。

    通过不注入(inject)代码,您:

    1. 保持轻松使用GM_函数的能力
    2. 避免或减少依赖外部服务器来交付库。
    3. 避免页面 JS 的潜在副作用和依赖性。 (您甚至可以使用 NoScript 之类的东西来完全禁用页面的 JS,而您的脚本仍在运行。)
    4. 防止恶意网站利用您的脚本来访问 GM_ 函数。

  2. 使用 the Tampermonkey extension ( Chrome )。这允许您通过提供更好的 Greasemonkey 仿真来避免脚本注入(inject)。您可以使用 @require 指令和比 Chrome 原生提供的更强大/更危险的 unsafeWindow 版本。

  3. 将您的用户脚本代码拆分为注入(inject)部分(不能使用 GM_ 函数)和非注入(inject)部分。使用 messaging 、轮询和/或特定 DOM 节点以在范围之间进行通信。



如果您真的必须使用注入(inject)代码,这里有一个演示如何执行此操作的示例脚本:

// ==UserScript==
// @name        _Fire GM_ function from injected code
// @include     https://stackoverflow.com/*
// @grant       GM_xmlhttpRequest
// ==/UserScript==
/* Warning:  Using @match versus @include can kill the Cross-domain ability of
    GM_xmlhttpRequest!  Bug?
*/

function InjectDemoCode ($) {
    $("body").prepend ('<button id="gmCommDemo">Open the console and then click me.</button>');

    $("#gmCommDemo").click ( function () {
        //--- This next value could be from the page's or the injected-code's JS.
        var fetchURL    = "http://www.google.com/";

        //--- Tag the message, in case there's more than one type flying about...
        var messageTxt  = JSON.stringify (["fetchURL", fetchURL])

        window.postMessage (messageTxt, "*");
        console.log ("Posting message");
    } );
}

withPages_jQuery (InjectDemoCode);

//--- This code listens for the right kind of message and calls GM_xmlhttpRequest.
window.addEventListener ("message", receiveMessage, false);

function receiveMessage (event) {
    var messageJSON;
    try {
        messageJSON     = JSON.parse (event.data);
    }
    catch (zError) {
        // Do nothing
    }
    console.log ("messageJSON:", messageJSON);

    if ( ! messageJSON) return; //-- Message is not for us.

    if (messageJSON[0] == "fetchURL") {
        var fetchURL    = messageJSON[1];

        GM_xmlhttpRequest ( {
            method:     'GET',
            url:        fetchURL,
            onload:     function (responseDetails) {
                            // DO ALL RESPONSE PROCESSING HERE...
                            console.log (
                                "GM_xmlhttpRequest() response is:\n",
                                responseDetails.responseText.substring (0, 80) + '...'
                            );
                        }
        } );
    }
}

function withPages_jQuery (NAMED_FunctionToRun) {
    //--- Use named functions for clarity and debugging...
    var funcText        = NAMED_FunctionToRun.toString ();
    var funcName        = funcText.replace (/^function\s+(\w+)\s*\((.|\n|\r)+$/, "$1");
    var script          = document.createElement ("script");
    script.textContent  = funcText + "\n\n";
    script.textContent += 'jQuery(document).ready( function () {' + funcName + '(jQuery);} );';
    document.body.appendChild (script);
};

关于javascript - 如何在注入(inject)代码中使用 GM_xmlhttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11377191/

相关文章:

javascript - "clicking"使用 javascript 没有 ID 的提交按钮

javascript - html/javascript 自动从提交按钮获取链接(也许用 python 自动化?)

javascript - Parse.com 无法从 Parse.User.current 获取用户名?

javascript - 如何禁用将十进制数转换为指数?

javascript - Webpack:未知属性 "query"?

html - 重新分配嵌套影子 DOM 中的重复插槽元素

javascript - 如何处理 404 页面上的权限被拒绝异常?

javascript - Chrome扩展程序-如何选择选项卡的所有文本并复制

javascript - 我可以在 chrome 扩展程序中找到带有选定文本的标签吗?

javascript - ReferenceError:未定义 GM_xmlhttpRequest