Skip to content
Advertisement

Undefined Json response from django backend to chrome extension alert

Hi i am trying to return a json file to the chrome extention to show it to the user, the query go to server without a problem, fetched url is also working and does return the json file when i try it directly, but the chrome extention shows "undefined" message in the alert instead of the json file.

the returned json file have this type : JsonResponse(data)

data is a dict[str, Union[str, list]],

another question, is how can I show the json file in the popup html page?

to my chrome extension code:

Manifest.json:

{
  "name": "Price Comparator",
  "description": "Compare prices across other websites!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "icons": {
    "16": "images/logo16.png",
    "48": "images/logo48.png",
    "128": "images/logo128.png"
  },
  "action": {
    "default_icon": "images/logo16.png",
    "default_popup": "popup.html"
  },
  "host_permissions": ["XXX*"],
  "permissions": [
    "XXX",
    "http://127.0.0.1:8000/",
    "storage",
    "activeTab",
    "scripting",
    "tabs",
    "background",
    "identity",
    "notifications"
  ],
  "content_scripts": [
    {
      "matches": [
        "https://www.google.com/*"
      ],
      "css": [
        "main.css"
      ]
    }
  ]
}

popup.js:

$(function(){

    
    $('#keywordsubmit').click(function(){
        
        var search_topic = $('#keyword').val();
        
                
        if (search_topic){
                chrome.runtime.sendMessage(
                    {topic: search_topic},
                    function(response) {
                        result = response.farewell;
                        alert(result.summary);
                        
                        var notifOptions = {
                            type: "basic",
                            iconUrl: "icon48.png",
                            title: "WikiPedia Summary For Your Result",
                        };
                        chrome.notifications.create('WikiNotif', notifOptions);
                        
                    });
        }
            
            
        $('#keyword').val('');
        
    });
});

Background.js:

chrome.runtime.onInstalled.addListener(() => { console.log('Extension is running!'); });

chrome.tabs.onActivated.addListener(function (activeInfo) {
    chrome.tabs.get(activeInfo.tabId, function (tab) {
        y = tab.url;
        console.log("you are here: " + tab.title);
    });
});

chrome.tabs.onUpdated.addListener((tabId, change, tab) => {
    if (tab.active && change.url) {
        console.log("you are here: " + change.url);
    }
});

var serverhost = 'XXXX';

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {


        var url = serverhost + '/wiki/get_wiki_summary/?topic=' + encodeURIComponent(request.topic);

        console.log(url);

        //var url = "http://127.0.0.1:8000/wiki/get_wiki_summary/?topic=%22COVID19%22"  
        fetch(url)
            .then(response => response.json())
            .then(response => sendResponse({ farewell: response }))
            .catch(error => console.log(error))
        return true;  // Will respond asynchronously.

    });

here is the python code:

  def get_wiki_summary(request):
query = request.GET.get('topic', None) +" XXXX"

user_agent_list = [
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:77.0) Gecko/20100101 Firefox/77.0',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36',
]
for i in range(1, 4):
    user_agent = random.choice(user_agent_list)

headers = {'User-Agent': user_agent}

## Google Search query results as a Python List of URLs
search_result_list = list(search(query, tld="de", num=1, stop=1, pause=1))

page = requests.get(search_result_list[0], headers=headers)
time.sleep(4)
soup = BeautifulSoup(page.text, "lxml")

with open("output1.html", "w", encoding="utf-8") as file:
    file.write(str(soup))

if soup.findAll(text="captcha") :
    return JsonResponse(search_result_list[0])


else:
    data = parsefile()

    return JsonResponse(data)

and the parse function:

def parsefile():
Productimage = {}

Products = {}
Images = {}
print(Products)
# Products = defaultdict(list)

with open('output1.html', 'r', encoding="utf-8") as f:
    html_string = f.read()
soup = BeautifulSoup(html_string, 'lxml')
prices = soup.find_all('a', {'class': 'productOffers-listItemOfferPrice'})

for elem in prices:
    oldlink = elem['href']
    elem['href'] = ("http://XXXX.de" + oldlink)
    # oldlink = requests.get(elem['href'])
    # print(oldlink.url)
    # elem['href']  = oldlink.headers['Location']
    # domain = urlparse(oldlink.url).netloc

    if "Website" not in Products:
        Products["Website"] = list()
    if "Link" not in Products:
        Products["Link"] = list()
    if "Price" not in Products:
        Products["Price"] = list()

    Products["Website"].append(elem['href'])
    Products["Price"].append(str((elem.get_text())))
    Products["Link"].append(elem['href'])

listimage = soup.find('img', {'class': 'datasheet-cover-image'})

if "Image" not in Images:
    Products["Image"] = str(listimage.get("src"))
data = {
    'summary': str(listimage.get("src")),
    'raw': 'Successful',

}

with open("prices.html", "w", encoding="utf-8") as file:
    file.write(str(prices))

with open('resultproducts.json', 'w', encoding="utf-8") as fp:
    json.dump(Products, fp)

return Products

Advertisement

Answer

All problem is in Python code.

In JavaScript you want to display summary

alert(result.summary);

and in Python in parsefile() you create

data = {
    'summary': str(listimage.get("src")),
    'raw': 'Successful',
}

but later you send Product instead of data

return Product

so your

data = parsefile()

return JsonResponse(data)

means

return JsonResponse(Product)

instead of

return JsonResponse({
           'summary': str(listimage.get("src")),
           'raw': 'Successful',
       })

In parsefile() you should do

return data

or

Product['summary'] = str(listimage.get("src"))
Product['raw'] = 'Successful'

return Product

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement