Skip to content

Instantly share code, notes, and snippets.

@HunterHeston
Forked from SafEight/notion2blog.js
Created May 3, 2020 17:32
Show Gist options
  • Select an option

  • Save HunterHeston/ac1b4c2e0a9f37a848e87b1ac8bc800b to your computer and use it in GitHub Desktop.

Select an option

Save HunterHeston/ac1b4c2e0a9f37a848e87b1ac8bc800b to your computer and use it in GitHub Desktop.

Revisions

  1. @SafEight SafEight revised this gist Feb 5, 2020. 1 changed file with 11 additions and 41 deletions.
    52 changes: 11 additions & 41 deletions notion2blog.js
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,5 @@
    const MY_DOMAIN = "agodrich.com"
    const START_PAGE = "https://www.notion.so/gatsby-starter-notion-2c5e3d685aa341088d4cd8daca52fcc2"
    const DISQUS_SHORTNAME = "agodrich"
    const MY_DOMAIN = "example.com"
    const START_PAGE = "https://www.notion.so/example"

    addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request))
    @@ -72,12 +71,12 @@ async function fetchAndApply(request) {
    method: request.method, // *GET, POST, PUT, DELETE, etc.
    })
    response = new Response(response.body, response)
    if (DISQUS_SHORTNAME) {
    // Delete CSP to load disqus content
    response.headers.delete("Content-Security-Policy")
    // add disqus comment component for every notion page
    return new HTMLRewriter().on('body', new ElementHandler()).transform(response)
    }

    // Delete CSP to load disqus content
    response.headers.delete("Content-Security-Policy")
    // add disqus comment component for every notion page
    return new HTMLRewriter().on('body', new ElementHandler()).transform(response)

    }
    return response
    }
    @@ -87,62 +86,34 @@ class ElementHandler {
    // An incoming element, such as `div`
    element.append(`
    <script>
    let disqus = document.createElement("div")
    disqus.id = "disqus_thread"
    disqus.style.width = "100%"
    var disqus_config = function () {
    let pathList = window.location.pathname.split("-")
    let pageID = pathList[pathList.length - 1]
    this.page.url = window.location.href;
    if (/^[\w]{32}$/.test(pageID)) {
    this.page.identifier = pageID;
    }else{
    this.page.identifier = undefined;
    }
    };
    (function () {
    var d = document, s = d.createElement('script');
    s.src = 'https://${DISQUS_SHORTNAME}.disqus.com/embed.js';
    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();
    // if you want to hide some element, add the selector to hideEle Array
    const hideEle = [
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(6)",
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(5)",
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(4)",
    ".notion-topbar > div:nth-child(1) > div:nth-child(5)",
    ]
    // if you want to replace some element, add the selector and innerHTML to replaceEle Object
    const replaceEle = {
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(6)": "<span>agodrich<span>"
    }
    function hideElement(qs) {
    let eles = document.querySelectorAll(qs)
    eles && eles.forEach(ele => ele.style.display = "none")
    }
    function replaceElement(qs, _html) {
    let ele = document.querySelector(qs)
    if (ele) {
    ele.innerHTML = _html
    }
    }
    let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    let body = document.querySelector('body');
    let observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
    let pageContent = document.querySelector("#notion-app div.notion-page-content")
    if (pageContent) {
    if (pageContent.lastChild && pageContent.lastChild.id !== "disqus_thread") {
    pageContent.append(disqus)
    DISQUS.reset({ reload: true })
    console.log(+new Date())
    }
    // Do nothing club
    }
    hideEle.forEach( hideE => hideElement(hideE) )
    Object.entries(replaceEle).forEach( item => {
    @@ -153,7 +124,6 @@ let observer = new MutationObserver(function (mutations) {
    });
    observer.observe(body, { subtree: true, childList: true });
    </script>
    <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    `, { html: Boolean })
    console.log(`Incoming element: ${element.tagName}`)
    }
    @@ -165,4 +135,4 @@ observer.observe(body, { subtree: true, childList: true });
    text(text) {
    // An incoming piece of text
    }
    }
    }
  2. @SafEight SafEight revised this gist Jan 30, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion notion2blog.js
    Original file line number Diff line number Diff line change
    @@ -147,7 +147,7 @@ let observer = new MutationObserver(function (mutations) {
    hideEle.forEach( hideE => hideElement(hideE) )
    Object.entries(replaceEle).forEach( item => {
    let [qs,_html] = item;
    replaceEle(qs,_html)
    replaceElement(qs,_html)
    })
    });
    });
  3. @mayneyao mayneyao revised this gist Jan 30, 2020. 1 changed file with 30 additions and 1 deletion.
    31 changes: 30 additions & 1 deletion notion2blog.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    const MY_DOMAIN = "agodrich.com"
    const START_PAGE = "https://notion.so/gatsby-starter-notion-2c5e3d685aa341088d4cd8daca52fcc2"
    const START_PAGE = "https://www.notion.so/gatsby-starter-notion-2c5e3d685aa341088d4cd8daca52fcc2"
    const DISQUS_SHORTNAME = "agodrich"

    addEventListener('fetch', event => {
    @@ -108,6 +108,30 @@ var disqus_config = function () {
    (d.head || d.body).appendChild(s);
    })();
    // if you want to hide some element, add the selector to hideEle Array
    const hideEle = [
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(6)",
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(5)",
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(4)",
    ]
    // if you want to replace some element, add the selector and innerHTML to replaceEle Object
    const replaceEle = {
    "#notion-app > div > div.notion-cursor-listener > div > div:nth-child(1) > div.notion-topbar > div > div:nth-child(6)": "<span>agodrich<span>"
    }
    function hideElement(qs) {
    let eles = document.querySelectorAll(qs)
    eles && eles.forEach(ele => ele.style.display = "none")
    }
    function replaceElement(qs, _html) {
    let ele = document.querySelector(qs)
    if (ele) {
    ele.innerHTML = _html
    }
    }
    let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    let body = document.querySelector('body');
    let observer = new MutationObserver(function (mutations) {
    @@ -120,6 +144,11 @@ let observer = new MutationObserver(function (mutations) {
    console.log(+new Date())
    }
    }
    hideEle.forEach( hideE => hideElement(hideE) )
    Object.entries(replaceEle).forEach( item => {
    let [qs,_html] = item;
    replaceEle(qs,_html)
    })
    });
    });
    observer.observe(body, { subtree: true, childList: true });
  4. @mayneyao mayneyao revised this gist Jan 11, 2020. 2 changed files with 139 additions and 74 deletions.
    74 changes: 0 additions & 74 deletions notion-custom-domain.js
    Original file line number Diff line number Diff line change
    @@ -1,74 +0,0 @@
    const MY_DOMAIN = "your domain"
    const START_PAGE = "start page url"

    addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request))
    })

    const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, HEAD, POST,PUT, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
    }

    function handleOptions(request) {
    if (request.headers.get("Origin") !== null &&
    request.headers.get("Access-Control-Request-Method") !== null &&
    request.headers.get("Access-Control-Request-Headers") !== null) {
    // Handle CORS pre-flight request.
    return new Response(null, {
    headers: corsHeaders
    })
    } else {
    // Handle standard OPTIONS request.
    return new Response(null, {
    headers: {
    "Allow": "GET, HEAD, POST, PUT, OPTIONS",
    }
    })
    }
    }

    async function fetchAndApply(request) {
    if (request.method === "OPTIONS") {
    return handleOptions(request)
    }
    let url = new URL(request.url)
    let response
    if (url.pathname.startsWith("/app") && url.pathname.endsWith("js")) {
    response = await fetch(`https://www.notion.so${url.pathname}`)
    let body = await response.text()
    try {
    response = new Response(body.replace(/www.notion.so/g, MY_DOMAIN).replace(/notion.so/g, MY_DOMAIN), response)
    // response = new Response(response.body, response)
    response.headers.set('Content-Type', "application/x-javascript")
    console.log("get rewrite app.js")
    } catch (err) {
    console.log(err)
    }

    } else if ((url.pathname.startsWith("/api"))) {
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: {
    'content-type': 'application/json;charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    })
    response = new Response(response.body, response)
    response.headers.set('Access-Control-Allow-Origin', "*")
    } else if (url.pathname === `/`) {
    let pageUrlList = START_PAGE.split("/")
    let redrictUrl = `https://${MY_DOMAIN}/${pageUrlList[pageUrlList.length-1]}`
    return Response.redirect(redrictUrl, 301)
    } else {
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: request.headers,
    method: request.method, // *GET, POST, PUT, DELETE, etc.
    })
    }

    return response
    }
    139 changes: 139 additions & 0 deletions notion2blog.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,139 @@
    const MY_DOMAIN = "agodrich.com"
    const START_PAGE = "https://notion.so/gatsby-starter-notion-2c5e3d685aa341088d4cd8daca52fcc2"
    const DISQUS_SHORTNAME = "agodrich"

    addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request))
    })

    const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, HEAD, POST,PUT, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
    }

    function handleOptions(request) {
    if (request.headers.get("Origin") !== null &&
    request.headers.get("Access-Control-Request-Method") !== null &&
    request.headers.get("Access-Control-Request-Headers") !== null) {
    // Handle CORS pre-flight request.
    return new Response(null, {
    headers: corsHeaders
    })
    } else {
    // Handle standard OPTIONS request.
    return new Response(null, {
    headers: {
    "Allow": "GET, HEAD, POST, PUT, OPTIONS",
    }
    })
    }
    }

    async function fetchAndApply(request) {
    if (request.method === "OPTIONS") {
    return handleOptions(request)
    }
    let url = new URL(request.url)
    let response
    if (url.pathname.startsWith("/app") && url.pathname.endsWith("js")) {
    // skip validation in app.js
    response = await fetch(`https://www.notion.so${url.pathname}`)
    let body = await response.text()
    try {
    response = new Response(body.replace(/www.notion.so/g, MY_DOMAIN).replace(/notion.so/g, MY_DOMAIN), response)
    response.headers.set('Content-Type', "application/x-javascript")
    console.log("get rewrite app.js")
    } catch (err) {
    console.log(err)
    }

    } else if ((url.pathname.startsWith("/api"))) {
    // Forward API
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: {
    'content-type': 'application/json;charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    })
    response = new Response(response.body, response)
    response.headers.set('Access-Control-Allow-Origin', "*")
    } else if (url.pathname === `/`) {
    // 301 redrict
    let pageUrlList = START_PAGE.split("/")
    let redrictUrl = `https://${MY_DOMAIN}/${pageUrlList[pageUrlList.length - 1]}`
    return Response.redirect(redrictUrl, 301)
    } else {
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: request.headers,
    method: request.method, // *GET, POST, PUT, DELETE, etc.
    })
    response = new Response(response.body, response)
    if (DISQUS_SHORTNAME) {
    // Delete CSP to load disqus content
    response.headers.delete("Content-Security-Policy")
    // add disqus comment component for every notion page
    return new HTMLRewriter().on('body', new ElementHandler()).transform(response)
    }
    }
    return response
    }

    class ElementHandler {
    element(element) {
    // An incoming element, such as `div`
    element.append(`
    <script>
    let disqus = document.createElement("div")
    disqus.id = "disqus_thread"
    disqus.style.width = "100%"
    var disqus_config = function () {
    let pathList = window.location.pathname.split("-")
    let pageID = pathList[pathList.length - 1]
    this.page.url = window.location.href;
    if (/^[\w]{32}$/.test(pageID)) {
    this.page.identifier = pageID;
    }else{
    this.page.identifier = undefined;
    }
    };
    (function () {
    var d = document, s = d.createElement('script');
    s.src = 'https://${DISQUS_SHORTNAME}.disqus.com/embed.js';
    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();
    let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    let body = document.querySelector('body');
    let observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
    let pageContent = document.querySelector("#notion-app div.notion-page-content")
    if (pageContent) {
    if (pageContent.lastChild && pageContent.lastChild.id !== "disqus_thread") {
    pageContent.append(disqus)
    DISQUS.reset({ reload: true })
    console.log(+new Date())
    }
    }
    });
    });
    observer.observe(body, { subtree: true, childList: true });
    </script>
    <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    `, { html: Boolean })
    console.log(`Incoming element: ${element.tagName}`)
    }

    comments(comment) {
    // An incoming comment
    }

    text(text) {
    // An incoming piece of text
    }
    }
  5. @mayneyao mayneyao renamed this gist Aug 16, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  6. @mayneyao mayneyao revised this gist Aug 16, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion cloudflare-wroker.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    const MY_DOMAIN = "your domain"
    const START_PAGE = "star page url"
    const START_PAGE = "start page url"

    addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request))
  7. @mayneyao mayneyao created this gist Aug 16, 2019.
    74 changes: 74 additions & 0 deletions cloudflare-wroker.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@
    const MY_DOMAIN = "your domain"
    const START_PAGE = "star page url"

    addEventListener('fetch', event => {
    event.respondWith(fetchAndApply(event.request))
    })

    const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, HEAD, POST,PUT, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type",
    }

    function handleOptions(request) {
    if (request.headers.get("Origin") !== null &&
    request.headers.get("Access-Control-Request-Method") !== null &&
    request.headers.get("Access-Control-Request-Headers") !== null) {
    // Handle CORS pre-flight request.
    return new Response(null, {
    headers: corsHeaders
    })
    } else {
    // Handle standard OPTIONS request.
    return new Response(null, {
    headers: {
    "Allow": "GET, HEAD, POST, PUT, OPTIONS",
    }
    })
    }
    }

    async function fetchAndApply(request) {
    if (request.method === "OPTIONS") {
    return handleOptions(request)
    }
    let url = new URL(request.url)
    let response
    if (url.pathname.startsWith("/app") && url.pathname.endsWith("js")) {
    response = await fetch(`https://www.notion.so${url.pathname}`)
    let body = await response.text()
    try {
    response = new Response(body.replace(/www.notion.so/g, MY_DOMAIN).replace(/notion.so/g, MY_DOMAIN), response)
    // response = new Response(response.body, response)
    response.headers.set('Content-Type', "application/x-javascript")
    console.log("get rewrite app.js")
    } catch (err) {
    console.log(err)
    }

    } else if ((url.pathname.startsWith("/api"))) {
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: {
    'content-type': 'application/json;charset=UTF-8',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
    },
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    })
    response = new Response(response.body, response)
    response.headers.set('Access-Control-Allow-Origin', "*")
    } else if (url.pathname === `/`) {
    let pageUrlList = START_PAGE.split("/")
    let redrictUrl = `https://${MY_DOMAIN}/${pageUrlList[pageUrlList.length-1]}`
    return Response.redirect(redrictUrl, 301)
    } else {
    response = await fetch(`https://www.notion.so${url.pathname}`, {
    body: request.body, // must match 'Content-Type' header
    headers: request.headers,
    method: request.method, // *GET, POST, PUT, DELETE, etc.
    })
    }

    return response
    }