How to grab the active tabs URL from an opend browser(64-bit Linux system) using python

i trying to make an desktop monitoring system for linux based OS. When I work with this code I get the currently opend applications in my system and browser tabs and its title also. But I want the urls too. If any one know about this please help. Here is my views.py file

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from django.http import JsonResponse
import subprocess
import re
import threading
import time
from urllib.parse import urlparse
opened_applications = []
def get_domain_name(url):
parsed_url = urlparse(url)
domain = parsed_url.netloc
if domain.startswith("www."):
domain = domain[4:] # Remove 'www.' if present
return domain
def extract_search_query(title):
# Common patterns indicating a search query in browser titles
search_patterns = ["Google Search", "Google", "Bing", "Yahoo", "DuckDuckGo"]
# Check if any of the search patterns are present in the title
for pattern in search_patterns:
if pattern.lower() in title.lower():
# Extract the search query using string manipulation
query_start_index = title.lower().find(pattern.lower()) + len(pattern)
search_query = title[query_start_index:].strip()
return search_query
return "Search Query Placeholder"
def monitor_opened_applications():
global opened_applications
try:
while True:
# Get a list of window titles using wmctrl
output = subprocess.check_output(["wmctrl", "-lx"]).decode("utf-8")
# Extract application names from window titles
new_opened_applications = []
for line in output.split("n"):
# print("++++++++++", line)
if line:
match = re.match(r"^(w+s+S+)s+(S+)s+(.+)$", line)
if match:
window_id = match.group(1)
desktop_id = match.group(2)
window_title = match.group(3)
# Check if either the Desktop ID or Window Title contains the word "browser"
is_browser_tab = (
"chrome" in desktop_id.lower()
or "firefox" in window_title.lower()
)
if is_browser_tab:
if (
"firefox" in window_title.lower()
or "chrome" in window_title.lower()
):
# Use regex to extract URL from the window title
url_match = re.search(
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
window_title,
)
if url_match:
url = url_match.group()
else:
url = "Unknown"
# Extract search query from the browser title
search_query = extract_search_query(window_title)
else:
url = "Unknown"
search_query = "Unknown"
else:
url = "Not a browser window"
search_query = "Not a browser window"
new_opened_applications.append(
{
"Window ID": window_id,
"Desktop ID": desktop_id,
"Window Title": window_title,
"URL": url,
"Search Query": search_query,
}
)
# Check for newly opened applications
new_apps = [
app for app in new_opened_applications if app not in opened_applications
]
if new_apps:
print("Newly opened applications:")
for app in new_apps:
print("Window ID:", app["Window ID"])
print("Desktop ID:", app["Desktop ID"])
print("Window Title:", app["Window Title"])
print("URL:", app["URL"])
print("Search Query:", app["Search Query"])
print()
# Update the list of opened applications
opened_applications = new_opened_applications
# Sleep for 5 seconds before checking again
time.sleep(5)
except subprocess.CalledProcessError:
# Print error message in case of failure
print("Failed to retrieve opened desktop applications.")
monitor_thread = threading.Thread(target=monitor_opened_applications)
monitor_thread.daemon = True
monitor_thread.start()
def get_opened_applications(request):
global opened_applications
try:
# Return the list of opened applications in JSON format
return JsonResponse(opened_applications, safe=False)
except Exception as e:
# Print error message in case of failure
print("Error:", str(e))
# Return an error response
return JsonResponse({"error": str(e)}, status=500)
</code>
<code>from django.http import JsonResponse import subprocess import re import threading import time from urllib.parse import urlparse opened_applications = [] def get_domain_name(url): parsed_url = urlparse(url) domain = parsed_url.netloc if domain.startswith("www."): domain = domain[4:] # Remove 'www.' if present return domain def extract_search_query(title): # Common patterns indicating a search query in browser titles search_patterns = ["Google Search", "Google", "Bing", "Yahoo", "DuckDuckGo"] # Check if any of the search patterns are present in the title for pattern in search_patterns: if pattern.lower() in title.lower(): # Extract the search query using string manipulation query_start_index = title.lower().find(pattern.lower()) + len(pattern) search_query = title[query_start_index:].strip() return search_query return "Search Query Placeholder" def monitor_opened_applications(): global opened_applications try: while True: # Get a list of window titles using wmctrl output = subprocess.check_output(["wmctrl", "-lx"]).decode("utf-8") # Extract application names from window titles new_opened_applications = [] for line in output.split("n"): # print("++++++++++", line) if line: match = re.match(r"^(w+s+S+)s+(S+)s+(.+)$", line) if match: window_id = match.group(1) desktop_id = match.group(2) window_title = match.group(3) # Check if either the Desktop ID or Window Title contains the word "browser" is_browser_tab = ( "chrome" in desktop_id.lower() or "firefox" in window_title.lower() ) if is_browser_tab: if ( "firefox" in window_title.lower() or "chrome" in window_title.lower() ): # Use regex to extract URL from the window title url_match = re.search( r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", window_title, ) if url_match: url = url_match.group() else: url = "Unknown" # Extract search query from the browser title search_query = extract_search_query(window_title) else: url = "Unknown" search_query = "Unknown" else: url = "Not a browser window" search_query = "Not a browser window" new_opened_applications.append( { "Window ID": window_id, "Desktop ID": desktop_id, "Window Title": window_title, "URL": url, "Search Query": search_query, } ) # Check for newly opened applications new_apps = [ app for app in new_opened_applications if app not in opened_applications ] if new_apps: print("Newly opened applications:") for app in new_apps: print("Window ID:", app["Window ID"]) print("Desktop ID:", app["Desktop ID"]) print("Window Title:", app["Window Title"]) print("URL:", app["URL"]) print("Search Query:", app["Search Query"]) print() # Update the list of opened applications opened_applications = new_opened_applications # Sleep for 5 seconds before checking again time.sleep(5) except subprocess.CalledProcessError: # Print error message in case of failure print("Failed to retrieve opened desktop applications.") monitor_thread = threading.Thread(target=monitor_opened_applications) monitor_thread.daemon = True monitor_thread.start() def get_opened_applications(request): global opened_applications try: # Return the list of opened applications in JSON format return JsonResponse(opened_applications, safe=False) except Exception as e: # Print error message in case of failure print("Error:", str(e)) # Return an error response return JsonResponse({"error": str(e)}, status=500) </code>
from django.http import JsonResponse
import subprocess
import re
import threading
import time
from urllib.parse import urlparse

opened_applications = []


def get_domain_name(url):
    parsed_url = urlparse(url)
    domain = parsed_url.netloc
    if domain.startswith("www."):
        domain = domain[4:]  # Remove 'www.' if present
    return domain


def extract_search_query(title):
    # Common patterns indicating a search query in browser titles
    search_patterns = ["Google Search", "Google", "Bing", "Yahoo", "DuckDuckGo"]

    # Check if any of the search patterns are present in the title
    for pattern in search_patterns:
        if pattern.lower() in title.lower():
            # Extract the search query using string manipulation
            query_start_index = title.lower().find(pattern.lower()) + len(pattern)
            search_query = title[query_start_index:].strip()
            return search_query
    return "Search Query Placeholder"


def monitor_opened_applications():
    global opened_applications
    try:
        while True:
            # Get a list of window titles using wmctrl
            output = subprocess.check_output(["wmctrl", "-lx"]).decode("utf-8")

            # Extract application names from window titles
            new_opened_applications = []
            for line in output.split("n"):
                # print("++++++++++", line)
                if line:
                    match = re.match(r"^(w+s+S+)s+(S+)s+(.+)$", line)
                    if match:
                        window_id = match.group(1)
                        desktop_id = match.group(2)
                        window_title = match.group(3)

                        # Check if either the Desktop ID or Window Title contains the word "browser"
                        is_browser_tab = (
                            "chrome" in desktop_id.lower()
                            or "firefox" in window_title.lower()
                        )

                        if is_browser_tab:
                            if (
                                "firefox" in window_title.lower()
                                or "chrome" in window_title.lower()
                            ):
                                # Use regex to extract URL from the window title
                                url_match = re.search(
                                    r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
                                    window_title,
                                )
                                if url_match:
                                    url = url_match.group()
                                else:
                                    url = "Unknown"

                                # Extract search query from the browser title
                                search_query = extract_search_query(window_title)
                            else:
                                url = "Unknown"
                                search_query = "Unknown"
                        else:
                            url = "Not a browser window"
                            search_query = "Not a browser window"

                        new_opened_applications.append(
                            {
                                "Window ID": window_id,
                                "Desktop ID": desktop_id,
                                "Window Title": window_title,
                                "URL": url,
                                "Search Query": search_query,
                            }
                        )

            # Check for newly opened applications
            new_apps = [
                app for app in new_opened_applications if app not in opened_applications
            ]
            if new_apps:
                print("Newly opened applications:")
                for app in new_apps:
                    print("Window ID:", app["Window ID"])
                    print("Desktop ID:", app["Desktop ID"])
                    print("Window Title:", app["Window Title"])
                    print("URL:", app["URL"])
                    print("Search Query:", app["Search Query"])
                    print()

            # Update the list of opened applications
            opened_applications = new_opened_applications

            # Sleep for 5 seconds before checking again
            time.sleep(5)

    except subprocess.CalledProcessError:
        # Print error message in case of failure
        print("Failed to retrieve opened desktop applications.")


monitor_thread = threading.Thread(target=monitor_opened_applications)
monitor_thread.daemon = True
monitor_thread.start()


def get_opened_applications(request):
    global opened_applications
    try:
        # Return the list of opened applications in JSON format
        return JsonResponse(opened_applications, safe=False)
    except Exception as e:
        # Print error message in case of failure
        print("Error:", str(e))
        # Return an error response
        return JsonResponse({"error": str(e)}, status=500)

Now the output is like this

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
0
Window ID "0x04e00003 5"
Desktop ID "skype.Skype"
Window Title "LAP-LNX-2156 Skype"
URL "Not a browser window"
Search Query "Not a browser window"
1
Window ID "0x03c000e4 2"
Desktop ID "Navigator.firefox"
Window Title "LAP-LNX-2156 Ask a public question - Stack Overflow — Mozilla Firefox"
URL "Unknown"
Search Query "Search Query Placeholder"
2
Window ID "0x06a00004 4"
Desktop ID "google-chrome.Google-chrome"
Window Title "LAP-LNX-2156 ProgramSpeaker- A Technical Blog for Web Users - Google Chrome"
URL "Unknown"
Search Query "Chrome"
</code>
<code> 0 Window ID "0x04e00003 5" Desktop ID "skype.Skype" Window Title "LAP-LNX-2156 Skype" URL "Not a browser window" Search Query "Not a browser window" 1 Window ID "0x03c000e4 2" Desktop ID "Navigator.firefox" Window Title "LAP-LNX-2156 Ask a public question - Stack Overflow — Mozilla Firefox" URL "Unknown" Search Query "Search Query Placeholder" 2 Window ID "0x06a00004 4" Desktop ID "google-chrome.Google-chrome" Window Title "LAP-LNX-2156 ProgramSpeaker- A Technical Blog for Web Users - Google Chrome" URL "Unknown" Search Query "Chrome" </code>
    
0   
Window ID   "0x04e00003  5"
Desktop ID  "skype.Skype"
Window Title    "LAP-LNX-2156 Skype"
URL "Not a browser window"
Search Query    "Not a browser window"
1   
Window ID   "0x03c000e4  2"
Desktop ID  "Navigator.firefox"
Window Title    "LAP-LNX-2156 Ask a public question - Stack Overflow — Mozilla Firefox"
URL "Unknown"
Search Query    "Search Query Placeholder"
2   
Window ID   "0x06a00004  4"
Desktop ID  "google-chrome.Google-chrome"
Window Title    "LAP-LNX-2156 ProgramSpeaker- A Technical Blog for Web Users - Google Chrome"
URL "Unknown"
Search Query    "Chrome"

I want to replace the unknown value of URL with exact URL.

I want to get the url values in my response, if anyone know please help

New contributor

ProgramSpeaker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật