Gess1t
Gess1t

Reputation: 81

Need help about sending variable from chrome extension to python

i wanted to make a small script that download "maps" automatically when the user open the ingame link. Once the link Open in chrome, the extension get the current URL and send it to python(this is where i'm stuck right now) and then close the tab if successful (since it will fail if the python script isn't running?). once in python i then proceed to download the map in question and add it to the Songs folder where the only thing he will to do is push F5

right now, i have these pieces of code:

Manifest.json:

{
    "name": "Osu!AltDownload",
    "version": "1.0",
    "description": "A requirement to make osu!AltDownload work",
    "permissions": ["tabs","http://localhost:5000/"],
    "background": {
        "scripts": ["Osu!AltDownload.js"],
        "persistant": false
    },
    "manifest_version": 2
}

Osu!AltDownload.js

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete') {
        chrome.tabs.query({active: true, currentWindow: true}, tabs => {
        let url = tabs[0].url;
        });
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:5000/",true);
        xhr.send(url); 
    }
})

The script that receive the links and download the "maps":

import browser_cookie3
import requests
from bs4 import BeautifulSoup as BS
import re
import os
def maplink(osupath):
    link = link #obtain link from POST ?
    if link.split("/",4[:4]) == ['https:', '', 'osu.ppy.sh', 'beatmapsets']:
        Download_map(osupath, link.split("#osu")[0])

def Download_map(osupath, link):
    cj = browser_cookie3.load()
    print("Downloading", link)
    headers = {"referer": link}
    with requests.get(link) as r:
        t = BS(r.text, 'html.parser').title.text.split("·")[0]
    with requests.get(link+"/download", stream=True, cookies=cj, headers=headers) as r:
        if r.status_code == 200:
        try:
            id = re.sub("[^0-9]", "", link)
            with open(os.path.abspath(osupath+"/Songs/"+id+" "+t+".osz"), "wb") as otp:
                otp.write(r.content)
        except:
            print("You either aren't connected on osu!'s website or you're limited by the API, in which case you now have to wait 1h and then try again.")

i would like to add in that i used these lines of codes in my extension:

var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:5000/",true);
xhr.send(url);

they come from one of my google searches but i don't really understand how i can handle POST request in python with that and i don't even know if i going the right way.

Some may say i haven't done much research at this subject but out of about 50 chrome tabs, i haven't really found anything that would really give me an idea of the right approach for this subject.

Upvotes: 0

Views: 723

Answers (1)

furas
furas

Reputation: 142661

You have to run web server to get http requests

You can use Flask for this.

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        #print(request.form)
        print(request.data)
    return "OK"

if __name__ == '__main__':
    app.run(port=5000)    

 

If you want to send only url then you can use even GET instead of POST and send as

 http://localhost:5000/?data=your_url

where your_url is what you get with tab[0].url.

xhr.open("GET", "http://localhost:5000/?data=" + url, true);
xhr.send();  // or maybe xhr.send(null);

And then you can get it with

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    print(request.args.get('data'))
    return "OK"
        
if __name__ == '__main__':
    app.run(port=5000)        

EDIT:

Example which tests Flask using directly JavaScript when you visit http://localhost:5000/test

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def index():
    print(request.args.get('data'))
    return "OK"

@app.route('/test/')
def test():
    return """
<script>
    var url = "https://stackoverflow.com/questions/65867136/need-help-about-sending-variable-from-chrome-extension-to-python/";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost:5000/?data=" + url, true);
    xhr.send(); 
</script>
"""            

if __name__ == '__main__':
    app.run(port=5000)        

Eventually I can test it with bookmarklet

javascript:{window.location='http://localhost:5000/?data='+encodeURIComponent(window.location.href)}

which I put as url in bookmark in favorites - but this reload page

or using modern fetch() (instead of old XMLHttpRequest()) and it doesn't reload page.

javascript:{fetch('http://localhost:5000/?data='+encodeURIComponent(window.location.href))}

Upvotes: 1

Related Questions