0

I've started writing a chrome extension that when I click a specific element it runs an ajax request. The bind and click on the element are working fine. I can see the ajax event is triggered and runs correctly.

I now want to do an action based on the return result of the ajax request. If the result is 1 I want to append a DIV to the body of the tab the element is on. If the result is 0 I wan to remove that DIV if it exists.

My manifest.json contains:

"background": {
        "scripts": ["jquery.js", "eventPage.js"],
        "persistent": false
    },
  
    "content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "css": ["styles.css"],
        "js": ["jquery.js", "script.js"]
    }
    ],
    "icons": { 
        "16": "logo16.png",
        "48": "logo48.png",
        "128": "logo128.png"
    },
    
    "browser_action": {
        "default_icon": "logo.png",
        "default_popup": "popup.html"
    }

My script.js contains the following which is called when the element is clicked.

cmd = 'http://192.168.0.1/lookup.php';
chrome.runtime.sendMessage({ cmd });

lookup.php runs a query and returns 1 (good) or 0 (bad)

My eventPage.js contains:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    
    $.ajax({
        type: "POST",
        url: msg.cmd,
        success: function(data) {
            console.log (data)
        },
        error: function(e) {
            alert("error");
        }
    });

});

Looking at the output of the eventPage I can see the return result, but I've not been able to work out if I can append or remove the DIV from the eventPage.

How do I return the result from the ajax request to script.js so I can append or remove the div ?

Thanks

Tom
  • 1,436
  • 24
  • 50
  • 1
    Add a callback to sendMessage() call and use `sendResponse` + `return true` in onMessage listener, [example](https://stackoverflow.com/a/55292071). – wOxxOm Feb 19 '21 at 18:16
  • @wOxxOm perfect thanks that has worked. If you want to make it an answer I will accept it. – Tom Feb 20 '21 at 12:18

0 Answers0