xmlhttprequestgm-xmlhttprequestgreasemonkey-4

GM.xmlHttpRequest: Received no URL Error


This script is run on a Amazon deals page:

// ==UserScript==
// @name     Unnamed Script 138015
// @version  1
//@include     http://www.amazon.in/*
// @grant       GM_setValue   
// @grant       GM_getValue  
// @grant       GM.xmlHttpRequest
// @grant       GM_xmlhttpRequest
// @grant       GM.addStyle
// @grant       GM.getResourceText
// @grant       GM.getValue
// @grant       GM.setValue
// @grant       GM.info
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// ==/UserScript==
var x=document.getElementById("dealTitle"); //fetches the URL
alert(x);
GM.xmlHttpRequest ( {
    method: "GET",
    url: x,
    onload: function (response) {
        var parser  = new DOMParser ();
        var doc         = parser.parseFromString (response.responseText, "text/html");
        var price  = document.getElementsByClassName("a-size-medium a-color-price")[0];
        $("body").prepend ('<h1>' + price + '</h1>');
    },
    onerror: function (e) {
        console.error ('**** error ', e);
    },
    onabort: function (e) {
        console.error ('**** abort ', e);
    },
    ontimeout: function (e) {
        console.error ('**** timeout ', e);
    }
} );

It shows the following error in the console log.

Error: GM.xmlHttpRequest: Received no URL.
Stack trace:
GM_xmlHttpRequest@user-script:null/Unnamed%20Script%20138015:572:21
userScript@user-script:null/Unnamed%20Script%20138015:504:1
scopeWrapper@user-script:null/Unnamed%20Script%20138015:632:9
@user-script:null/Unnamed%20Script%20138015:487:17

Is there any way to use the link fetched from the page to be sent in the HttpRequest?


Solution

    1. getElementById does not return a URL; it returns a node.
    2. The dealTitle element is added via AJAX; it does not exist when your script first runs. So, you need to use AJAX-aware techniques in your script.

    Something like this should work:

    // ==UserScript==
    // @name        Unnamed Script 138015
    // @version     2
    // @match       *://www.amazon.in/*
    // @grant       GM.xmlHttpRequest
    // @grant       GM_xmlhttpRequest
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
    // ==/UserScript==
    
    waitForKeyElements ("#dealTitle", fetchDealPage);
    
    function fetchDealPage (jNode) {
        var dURL = jNode.attr ("href");
        console.log ("dURL: ", dURL);
    
        GM.xmlHttpRequest ( {
            method: "GET",
            url: dURL,
        //etc...
    }
    

    Although you may have to install Tampermonkey, and change the line to GM_xmlhttpRequest ( {.
    Not sure GM4 supports using GM.xmlHttpRequest that way.