Skip to content

Instantly share code, notes, and snippets.

@choco-la
Created November 29, 2017 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choco-la/542096ab6a29e4c0e8d2034abb28bf62 to your computer and use it in GitHub Desktop.
Save choco-la/542096ab6a29e4c0e8d2034abb28bf62 to your computer and use it in GitHub Desktop.
third-party cookiesを無効にしつつニコニコ動画の埋め込みを再生するやつ(未完成)
(function() {
'use strict'
let nicosid = ''
let nicohistory = ''
const assignFromSetCookieHeader = (cookie) => {
const values = cookie.split(';')
for (const value of values) {
const sid = /^nicosid=([0-9.]+)$/.exec(value)
if (sid) nicosid = sid[1]
const history = /^nicohistory=([a-zA-Z0-9%]+)$/.exec(value)
if (history) nicohistory = history[1]
}
}
const onHeadersReceived = (details) => {
for (const header of details.responseHeaders) {
if (header.name.toLowerCase() === 'set-cookie') {
assignFromSetCookieHeader(header.value)
break
}
}
return {'responseHeaders': details.responseHeaders}
}
const toPass = (details) => {
const isNicoVideo = /^https?:\/\/[^\/]+\.nicovideo\.jp\//.test(details.url)
if (!isNicoVideo) return true
if (details.url === 'https://nmsg.nicovideo.jp/api.json/') return true
if (details.method === 'OPTIONS') return true
return false
}
const getNicoCookieValues = () => {
if (nicosid.length > 0 && nicohistory.length > 0) {
return `nicosid=${nicosid}; nicohistory=${nicohistory}`
} else if (nicosid.length > 0) {
return `nicosid=${nicosid}`
} else if (nicohistory.length > 0) {
return `nicohistory=${nicohistory}`
} else {
return null
}
}
const onBeforeSendHeaders = (details) => {
if (toPass(details)) return details
const setCookie = getNicoCookieValues()
if (setCookie === null) return details
let isCookieSet = false
for (const header of details.requestHeaders) {
if (header.name.toLowerCase() !== 'cookie') continue
if (header.value) header.value = `${header.value}; ${setCookie}`
else header.value = setCookie
isCookieSet = true
break
}
if (!isCookieSet) details.requestHeaders.push({name: 'Cookie', value: setCookie})
return details
}
browser.webRequest.onHeadersReceived.addListener(
onHeadersReceived,
{urls: ['https://*.nicovideo.jp/*']},
['blocking', 'responseHeaders']
)
browser.webRequest.onBeforeSendHeaders.addListener(
onBeforeSendHeaders,
{urls: ['https://*.nicovideo.jp/*']},
['blocking', 'requestHeaders']
)
})()
{
"manifest_version": 2,
"name": "Watch",
"version": "0.1",
"applications": {
"gecko": {
"strict_min_version": "57.0a1",
"id": "watch@example.com"
}
},
"permissions": [
"webRequest",
"webRequestBlocking",
"tabs",
"https://friends.nico/web/*",
"https://friends.nico/nicomment",
"https://*.nicovideo.jp/*"
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment