Search code examples
javascriptgreasemonkey

href not working in greasemokey


I have following code in my greasemonkey script. In case, i am unable to save my order to server, i display an error message and then a link (created using <a href> to save it again. this link is save_order method again. But this is not working. I tried debugging into it but no luck. (I have basic understanding of JavaScript)

function save_order() {
    server_url = 'https://server.com/api/put_order?user_id=' + form.user.value +'&order_id=' + orderId;
    GM_xmlhttpRequest({
        method: "GET",
        url: server_url,
        onload: function(response){
            if(response.status == 200){
                localstorage.removeItem(orderId);
                messageBar.innerHTML += '<br/>Order has been saved successfully.';
            } else {
                if (errorBar.style.display === 'none'){
                    errorBar.style.display = 'block';
                }
                errorBar.innerHTML += '<br/>Error saving. <a href="#" onclick="save_order();return false"><b>Try Again</b></a>';
            }
        }
    });
}

=======

FULL CODE

// ==UserScript==
// @name         SaveOrder
// @version      1.0
// @author       myname
// @include      https://xx*.xxxxxxxx.com*/*
// @run-at       document-end
// @grant        GM_xmlhttpRequest
// ==/UserScript==

var saveButton = document.getElementById('save-button');
saveButton.addEventListener("click", save_order,true);
var info_bar = document.getElementById('info_bar');
var error_bar = document.getElementById('error_bar');
var form = document.getElementById('place_order_form');
var order_id = form.order_id.value;

var localstorage = window.localStorage;

if (localstorage.getItem(order_id)){
    save_to_db();
} 

function save_order(){
    localstorage.setItem(order_id, order_id);
}

function save_to_db() {
    var random_boolean = false;//Math.random() >= 0.5;

    console.log(random_boolean);

    server_url = 'https://xxx.xxxx.com/api/put_order?user_id=' + form.user.value +'&order_id=' + order_id;
    GM_xmlhttpRequest({
        method: "GET",
        url: server_url,
        onload: function(response){
            if(response.status == 200 && random_boolean){
                localstorage.removeItem(order_id);
                info_bar.innerHTML += '<br/>Order saved successfully';
            } else {
                if (error_bar.style.display === 'none'){
                    error_bar.style.display = 'block';
                }
                error_bar.innerHTML += '<br/>Error saving. <a href="#" onclick="save_to_db();"><b>Try Again</b></a>';
            }
        }
    });
}

Solution

  • Your method works just fine, as you can see in this example.

    You probably have an error elsewhere.

    function test(){
      document.body.innerHTML += '<a class="function-link" href="#" onclick="test();">Test</a>';
    }
    <a class="function-link" href="#" onclick="test();">Test</a>

    EDIT : I did some digging, and found a way around your issue.

    Instead of adding an onclick on your link, create an event handler in javascript attached to a save-to-db class like this :

    document.addEventListener("click", function(e) {
        if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
            save_to_db();
        }
    });
    

    Now all you need to do is get rid of your onclick and replace it with class="save-to-db"

    document.body.innerHTML += '<br/>Error saving. <a href="#" class="save-to-db"><b>Try Again</b></a>';
    

    It works like a charm now :

    document.addEventListener("click", function(e) {
        if (e.target.closest('a') && e.target.closest('a').classList.contains("save-to-db")) {
            save_to_db();
        }
    });
    
    save_to_db();
    
    function save_to_db() {
        console.log('Function called');
        document.body.innerHTML += '<br/>Error saving. <a href="#" class="save-to-db"><b>Try Again</b></a>';
    }