from mitmproxy import http

POLYFILL = """<script>
if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.webkitMatchesSelector;
}
if (!Element.prototype.closest) {
  Element.prototype.closest = function (s) {
    var el = this;
    while (el && el.nodeType === 1) {
      if (el.matches(s)) return el;
      el = el.parentNode;
    }
    return null;
  };
}
</script>"""

def response(flow: http.HTTPFlow):
    if not flow.request.host.endswith("flightradar24.com"):
        return
    ct = flow.response.headers.get("content-type", "")
    if "text/html" in ct and "<head>" in flow.response.text:
        flow.response.text = flow.response.text.replace("<head>", "<head>" + POLYFILL, 1)