Created
October 5, 2010 15:48
-
-
Save smizell/611766 to your computer and use it in GitHub Desktop.
Chrome Frame Django Middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
class ChromeFrameMiddleware(object): | |
""" | |
Adds the Google Chrome Frame meta tag to your page | |
If you don't want it to check if Chrome Frame is installed, | |
put this in your settings.py file. | |
CHROME_CHECK = False | |
""" | |
frame_tag = '<meta http-equiv="X-UA-Compatible" content="chrome=1">' | |
cfinstall_tag ="""<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1.0.2/CFInstall.min.js"></script> | |
<script>CFInstall.check()</script>""" | |
def __init__(self): | |
self.process_response = self.insert_tag | |
if getattr(settings, 'CHROME_CHECK', True): | |
self.process_response = self.chrome_check | |
def chrome_check(self, request, response): | |
if 'HTTP_USER_AGENT' in request.META: | |
if request.META['HTTP_USER_AGENT'].find('chromeframe') == -1: | |
body = response.content.lower().find('</body>') | |
if body != 1: | |
response.content = response.content[:body] + self.cfinstall_tag + response.content[body:] | |
return response | |
return self.insert_tag(request, response) | |
def insert_tag(self, request, response): | |
# Allows you to turn off Chrome per request | |
if 'no_chrome' in request.GET: | |
return response | |
# Find the head, and insert tag right before its closing tag | |
head = response.content.lower().find('</head>') | |
if head == -1: | |
return response | |
# Return new response | |
response.content = response.content[:head] + self.frame_tag + response.content[head:] | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment