clean up cross-origin request code

This commit is contained in:
ccd0 2014-08-03 18:34:02 -07:00
parent 689372e2b3
commit e70cdc620a
3 changed files with 19 additions and 25 deletions

View File

@ -1,6 +1,6 @@
CrossOrigin = do ->
handleBlob = (urlBlob, contentType, contentDisposition, url, cb) ->
makeBlob = (urlBlob, contentType, contentDisposition, url) ->
name = url.match(/([^\/]+)\/*$/)?[1]
mime = contentType?.match(/[^;]*/)[0] or 'application/octet-stream'
match =
@ -10,25 +10,20 @@ CrossOrigin = do ->
name = match.replace /\\"/g, '"'
blob = new Blob([urlBlob], {type: mime})
blob.name = name
cb blob
blob
handleUrl = (url, cb) ->
file = (url, cb) ->
<% if (type === 'crx') { %>
xhr = new XMLHttpRequest();
xhr.open('GET', url, true)
xhr.responseType = 'blob'
xhr.onload = (e) ->
if @readyState is @DONE && xhr.status is 200
contentType = @getResponseHeader('Content-Type')
contentDisposition = @getResponseHeader('Content-Disposition')
handleBlob @response, contentType, contentDisposition, url, cb
else
$.ajax url,
responseType: 'blob'
onload: ->
return cb null unless @readyState is @DONE and @status is 200
contentType = @getResponseHeader 'Content-Type'
contentDisposition = @getResponseHeader 'Content-Disposition'
cb (makeBlob @response, contentType, contentDisposition, url)
onerror: ->
cb null
xhr.onerror = (e) ->
cb null
xhr.send()
<% } %>
<% if (type === 'userscript') { %>
GM_xmlhttpRequest
method: "GET"
@ -36,17 +31,16 @@ CrossOrigin = do ->
overrideMimeType: "text/plain; charset=x-user-defined"
onload: (xhr) ->
r = xhr.responseText
data = new Uint8Array(r.length)
data = new Uint8Array r.length
i = 0
while i < r.length
data[i] = r.charCodeAt(i)
data[i] = r.charCodeAt i
i++
contentType = xhr.responseHeaders.match(/Content-Type:\s*(.*)/i)?[1]
contentType = xhr.responseHeaders.match(/Content-Type:\s*(.*)/i)?[1]
contentDisposition = xhr.responseHeaders.match(/Content-Disposition:\s*(.*)/i)?[1]
handleBlob data, contentType, contentDisposition, url, cb
onerror: (xhr) ->
cb (makeBlob data, contentType, contentDisposition, url)
onerror: ->
cb null
<% } %>
return {request: handleUrl}
{file}

View File

@ -10,7 +10,7 @@ DownloadLink =
$.on a, 'click', (e) ->
return true if @protocol is 'blob:'
e.preventDefault()
CrossOrigin.request @href, (blob) =>
CrossOrigin.file @href, (blob) =>
if blob
@href = URL.createObjectURL blob
@click()

View File

@ -290,7 +290,7 @@ QR =
handleUrl: ->
url = prompt("Insert an url:")
return if url is null
CrossOrigin.request url, (blob) ->
CrossOrigin.file url, (blob) ->
if blob
QR.handleFiles([blob])
else