Jump to content

Recommended Posts


Olá, tudo bem? Espero que sim.

 

Eu seguir esse tutorial e essa atualização para conseguir o código final. Mas o meu site fica totalmente, não exibe absolutamente nada. Eu venho aqui recorrer a vocês, pois lá não irei ter nenhum tipo de suporte. Por favor, quem for me auxiliar com esse pequeno problema, leia o tópico do tutorial. Mas o Fruition é um script para personalizar o domínio utilizando o Notion.

/* CONFIGURATION STARTS HERE */

  /* Step 1: enter your domain name like fruitionsite.com */
  const MY_DOMAIN = 'DOMINIO';
  
  /*
   * Step 2: enter your URL slug to page ID mapping
   * The key on the left is the slug (without the slash)
   * The value on the right is the Notion page ID
   */
  const SLUG_TO_PAGE = {
    '': 'CODIGO_DA_PÁGINA_PÚBLICA_DO_NOTION'
  };
  
  /* Step 3: enter your page title and description for SEO purposes */
  const PAGE_TITLE = '';
  const PAGE_DESCRIPTION = '';
  
  /* Step 4: enter a Google Font name, you can choose from https://fonts.google.com */
  const GOOGLE_FONT = '';
  
  /* Step 5: enter any custom scripts you'd like */
  const CUSTOM_SCRIPT = ``;
  
  /* CONFIGURATION ENDS HERE */
  
const PAGE_TO_SLUG = {};
const slugs = [];
const pages = [];
Object.keys(SLUG_TO_PAGE).forEach(slug => {
  const page = SLUG_TO_PAGE[slug];
  slugs.push(slug);
  pages.push(page);
  PAGE_TO_SLUG[page] = slug;
});

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

function generateSitemap() {
  let sitemap = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
  slugs.forEach(
    (slug) =>
      (sitemap +=
        "<url><loc>https://" + MY_DOMAIN + "/" + slug + "</loc></url>")
  );
  sitemap += "</urlset>";
  return sitemap;
}

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);
  url.hostname = 'www.notion.so';
  if (url.pathname === "/robots.txt") {
    return new Response("Sitemap: https://" + MY_DOMAIN + "/sitemap.xml");
  }
  if (url.pathname === "/sitemap.xml") {
    let response = new Response(generateSitemap());
    response.headers.set("content-type", "application/xml");
    return response;
  }
  let response;
  if (url.pathname.startsWith("/app") && url.pathname.endsWith("js")) {
    response = await fetch(url.toString());
    let body = await response.text();
    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");
    return response;
  } else if (url.pathname.startsWith("/api")) {
    // Forward API
    response = await fetch(url.toString(), {
      body: request.body,
      headers: {
        "content-type": "application/json;charset=UTF-8",
        "user-agent":
          "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
      },
      method: "POST"
    });
    response = new Response(response.body, response);
    response.headers.set("Access-Control-Allow-Origin", "*");
    return response;
  } else if (slugs.indexOf(url.pathname.slice(1)) > -1) {
    const pageId = SLUG_TO_PAGE[url.pathname.slice(1)];
    return Response.redirect("https://" + MY_DOMAIN + "/" + pageId, 301);
  } else {
    response = await fetch(url.toString(), {
      body: request.body,
      headers: request.headers,
      method: request.method
    });
    response = new Response(response.body, response);
    response.headers.delete("Content-Security-Policy");
    response.headers.delete("X-Content-Security-Policy");
  }

  return appendJavascript(response, SLUG_TO_PAGE);
}

class MetaRewriter {
  element(element) {
    if (PAGE_TITLE !== "") {
      if (
        element.getAttribute("property") === "og:title" ||
        element.getAttribute("name") === "twitter:title"
      ) {
        element.setAttribute("content", PAGE_TITLE);
      }
      if (element.tagName === "title") {
        element.setInnerContent(PAGE_TITLE);
      }
    }
    if (PAGE_DESCRIPTION !== "") {
      if (
        element.getAttribute("name") === "description" ||
        element.getAttribute("property") === "og:description" ||
        element.getAttribute("name") === "twitter:description"
      ) {
        element.setAttribute("content", PAGE_DESCRIPTION);
      }
    }
    if (
      element.getAttribute("property") === "og:url" ||
      element.getAttribute("name") === "twitter:url"
    ) {
      element.setAttribute("content", MY_DOMAIN);
    }
    if (element.getAttribute("name") === "apple-itunes-app") {
      element.remove();
    }
  }
}

class HeadRewriter {
  element(element) {
    if (GOOGLE_FONT !== "") {
      element.append(
        `<link href='https://fonts.googleapis.com/css?family=${GOOGLE_FONT.replace(' ', '+')}:Regular,Bold,Italic&display=swap' rel='stylesheet'>
        <style>* { font-family: "${GOOGLE_FONT}" !important; }</style>`,
        {
          html: true
        }
      );
    }
    element.append(
      `<style>
      div.notion-topbar > div > div:nth-child(3) { display: none !important; }
      div.notion-topbar > div > div:nth-child(4) { display: none !important; }
      div.notion-topbar > div > div:nth-child(5) { display: none !important; }
      div.notion-topbar > div > div:nth-child(6) { display: none !important; }
      div.notion-topbar-mobile > div:nth-child(3) { display: none !important; }
      div.notion-topbar-mobile > div:nth-child(4) { display: none !important; }
      div.notion-topbar > div > div:nth-child(1n).toggle-mode { display: block !important; }
      div.notion-topbar-mobile > div:nth-child(1n).toggle-mode { display: block !important; }
      </style>`,
      {
        html: true
      }
    );
  }
}

class BodyRewriter {
  constructor(SLUG_TO_PAGE) {
    this.SLUG_TO_PAGE = SLUG_TO_PAGE;
  }
  element(element) {
    element.append(
      `<script>
      const SLUG_TO_PAGE = ${JSON.stringify(this.SLUG_TO_PAGE)};
      const PAGE_TO_SLUG = {};
      const slugs = [];
      const pages = [];
      const el = document.createElement('div');
      let redirected = false;
      Object.keys(SLUG_TO_PAGE).forEach(slug => {
        const page = SLUG_TO_PAGE[slug];
        slugs.push(slug);
        pages.push(page);
        PAGE_TO_SLUG[page] = slug;
      });
      function getPage() {
        return location.pathname.slice(-32);
      }
      function getSlug() {
        return location.pathname.slice(1);
      }
      function updateSlug() {
        const slug = PAGE_TO_SLUG[getPage()];
        if (slug != null) {
          history.replaceState(history.state, '', '/' + slug);
        }
      }
      function onDark() {
        el.innerHTML = '<div title="Change to Light Mode" style="margin-left: auto; margin-right: 14px; min-width: 0px;"><div role="button" tabindex="0" style="user-select: none; transition: background 120ms ease-in 0s; cursor: pointer; border-radius: 44px;"><div style="display: flex; flex-shrink: 0; height: 14px; width: 26px; border-radius: 44px; padding: 2px; box-sizing: content-box; background: rgb(46, 170, 220); transition: background 200ms ease 0s, box-shadow 200ms ease 0s;"><div style="width: 14px; height: 14px; border-radius: 44px; background: white; transition: transform 200ms ease-out 0s, background 200ms ease-out 0s; transform: translateX(12px) translateY(0px);"></div></div></div></div>';
        document.body.classList.add('dark');
        __console.environment.ThemeStore.setState({ mode: 'dark' });
      };
      function onLight() {
        el.innerHTML = '<div title="Change to Dark Mode" style="margin-left: auto; margin-right: 14px; min-width: 0px;"><div role="button" tabindex="0" style="user-select: none; transition: background 120ms ease-in 0s; cursor: pointer; border-radius: 44px;"><div style="display: flex; flex-shrink: 0; height: 14px; width: 26px; border-radius: 44px; padding: 2px; box-sizing: content-box; background: rgba(135, 131, 120, 0.3); transition: background 200ms ease 0s, box-shadow 200ms ease 0s;"><div style="width: 14px; height: 14px; border-radius: 44px; background: white; transition: transform 200ms ease-out 0s, background 200ms ease-out 0s; transform: translateX(0px) translateY(0px);"></div></div></div></div>';
        document.body.classList.remove('dark');
        __console.environment.ThemeStore.setState({ mode: 'light' });
      }
      function toggle() {
        if (document.body.classList.contains('dark')) {
          onLight();
        } else {
          onDark();
        }
      }
      function addDarkModeButton(device) {
        const nav = device === 'web' ? document.querySelector('.notion-topbar').firstChild : document.querySelector('.notion-topbar-mobile');
        el.className = 'toggle-mode';
        el.addEventListener('click', toggle);
        nav.appendChild(el);
        onLight();
      }
      const observer = new MutationObserver(function() {
        if (redirected) return;
        const nav = document.querySelector('.notion-topbar');
        const mobileNav = document.querySelector('.notion-topbar-mobile');
        if (nav && nav.firstChild && nav.firstChild.firstChild
          || mobileNav && mobileNav.firstChild) {
          redirected = true;
          updateSlug();
          addDarkModeButton(nav ? 'web' : 'mobile');
          const onpopstate = window.onpopstate;
          window.onpopstate = function() {
            if (slugs.includes(getSlug())) {
              const page = SLUG_TO_PAGE[getSlug()];
              if (page) {
                history.replaceState(history.state, 'bypass', '/' + page);
              }
            }
            onpopstate.apply(this, [].slice.call(arguments));
            updateSlug();
          };
        }
      });
      observer.observe(document.querySelector('#notion-app'), {
        childList: true,
        subtree: true,
      });
      const replaceState = window.history.replaceState;
      window.history.replaceState = function(state) {
        if (arguments[1] !== 'bypass' && slugs.includes(getSlug())) return;
        return replaceState.apply(window.history, arguments);
      };
      const pushState = window.history.pushState;
      window.history.pushState = function(state) {
        const dest = new URL(location.protocol + location.host + arguments[2]);
        const id = dest.pathname.slice(-32);
        if (pages.includes(id)) {
          arguments[2] = '/' + PAGE_TO_SLUG[id];
        }
        return pushState.apply(window.history, arguments);
      };
      const open = window.XMLHttpRequest.prototype.open;
      window.XMLHttpRequest.prototype.open = function() {
        arguments[1] = arguments[1].replace('${MY_DOMAIN}', 'www.notion.so');
        return open.apply(this, [].slice.call(arguments));
      };
    </script>${CUSTOM_SCRIPT}`,
      {
        html: true
      }
    );
  }
}

async function appendJavascript(res, SLUG_TO_PAGE) {
  return new HTMLRewriter()
    .on("title", new MetaRewriter())
    .on("meta", new MetaRewriter())
    .on("head", new HeadRewriter())
    .on("body", new BodyRewriter(SLUG_TO_PAGE))
    .transform(res);
}

 


Tem alguma coisa de errado?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By _marlon307
      Boa noite. Bom Dia.
      Estou com um problema com meu menu hover em React. quando eu passo o mouse em cima do elemnto para abrir o menu le renderiza todas as abas e quando passo o mouse sobre o menu ele fica bugado.
       
      import React, { useState } from 'react'; import { Link } from 'react-router-dom'; //import DropModMn from '../../Helper/DropModMn'; import { ReactComponent as Respponse } from '../../icons/respponse.svg'; import styles from '../css/search.module.css'; import SubMenuCtg from './SubMneu/SubMenuCtg';   const Search = () => {       const menu = [         {             nctg: 'Masculino',             ctg: ['Categoria', 'Categoria', 'Categoria 3', 'Categoria 4', 'Categoria 5'],         },         {             nctg: 'Femenino',             ctg: ['Categoria 3', 'Categoria 4', 'Categoria 5', 'Categoria 6', 'Categoria 7'],         },         {             nctg: 'Criança',             ctg: ['Categoria 8', 'Categoria 9', 'Categoria 10', 'Categoria 11', 'Categoria 12'],         },         {             nctg: 'Acessórios',             ctg: ['Categoria 13', 'Categoria 14', 'Categoria 15', 'Categoria 16', 'Categoria 17'],         },         {             nctg: 'Promoção',             ctg: ['Categoria 18', 'Categoria 19', 'Categoria 20', 'Categoria 21', 'Categoria 22', 'Categoria 22', 'Categoria 22', 'Categoria 22', 'Categoria 22', 'Categoria 22', 'Categoria 22'],         }       ];      const [expand, setExpand] = useState(false);       function MouseOver(event){         event.preventDefault();                  console.log(event);           if(expand) setExpand(!expand);         else setExpand(!expand);     }       return (           <nav className={styles.search}>               <div className={styles.ct}>                 <Link to="/" className={styles.index}>                     <Respponse aria-label="Respponse"/>                 </Link>               </div>               <div className={styles.ct}>                   <ul className={styles.ldep}>                       {menu.map((m) =>                                                  <li className={styles.ictg} key={m.nctg} onMouseOver={MouseOver} onMouseLeave={MouseOver}>                               <Link className={`${styles.lctg} imh`} to={m.nctg}>{m.nctg}</Link>                                                          <SubMenuCtg gl={m.ctg} exp={expand} />                                                    </li>                     )}                                      </ul>             </div>         </nav>     ) }   export default Search
    • By Fluk
      Bom dia Galera, 
      Sou novo por aqui, estou estudando um pouco sobre o Google Script e Java Script. 

      Estou tentando criar um programinha que lê e exibe em tela os dados que estão armazenados em minha Base (FibreBase). 
      Mas quando tento puxar através da API Google google.script.run.minhaFunção() e salvar em uma variável o JavaScript passa direto não aguardando o fim da leitura de arquivo. 
      Dei uma lida sobre ser assíncrona a requisição que estou fazendo, mazers tentei de varias forma fa aguardar mas não consegui. 

       
      document.getElementById('ConsultarClientes').addEventListener( 'click',   function (){     // Buscar dados  FireBase Lista de Clientes     const clientes = getFireBase('Clientes/Arquivos');     clientes.then(retorno => console.log(retorno));   } ,false);   async function getFireBase(chave){   return google.script.run.withSuccessHandler().getFireBase(chave); };   Console log retorno
       
    • By SingleSistemas
      Olá, estou escrevendo um código aonde preciso colocar o JSON dentro de uma array, porém, o JSON foi parciado utilizando o JSON.parse, para atribuir o conteudo do document.todosOsFretes, segue o exemplo:  
      Queria saber qual alternativa que pode ser feita para mim poder colocar o document.todosOsFretes dentro de uma array e pesquisar nele, algum campo...
      Desde já agradeço.
       
       
       
       

    • By marceloDiegues
      Olá, amigos.
      Por favor,  me ajude com a seguintes perguntas.
       
      Qual a complexidade de um projeto desse?
      Qual o preçp de um projeto desse tipo?
       
      Quero contratar algum profissional para criar um site que tenha as seguintes funcionabilidades:
       
      1- Cadastro de usuário;
      2- Login e senha;
      3- O site seria muito parecido com o www.qconcursos.com, o usuário resolveria questões online.
      Contudo, haveria a possibilidade de criar salas tipo aqueles bate-papo da &nbsp;UOL.
      Então, o usuário criaria salas de estudos, em que , resolveria questões e conseguiria se comunicar por chat com usuários que estejam na mesma sala.
       
      Exemplo em anexo:
       
       
       
       

    • By Rodrigo Biaggio
      Pessoal, alguém consegue me ajudar? Eu preciso pegar os dados de um array, mas não estou conseguindo. 
       
      <!DOCTYPE html> <!-- Inicio do html --> <html lang="pt"> <!-- Inicio do head --> <head> <meta charset="utf-8"> <script src='https://kit.fontawesome.com/a076d05399.js'></script> <link rel="icon" type="imagem/png" href="images/dynatrace.png" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://unpkg.com/@popperjs/core@2/dist/umd/popper.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://unpkg.com/@popperjs/core@2"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <meta http-equiv="x-ua-compatible" content="ie=edge"> <!-- CSS Customizado --> <link href="css/ambiente-monitorado.css" rel="stylesheet"> </head> <!-- Fim do head --> <!-- Inicio do body --> <body> <header> <title>Dynatrace Managed</title> <!-- Inicio do nav fixado no topo--> <div id="nav"> <nav class="navbar navbar-inverse navbar-fixed-top"> <!-- Inicio div container-fluid --> <div class="container-fluid"> <div class="navbar-header"> <!-- Imagem do logo da Dynatrace a esquerda --> <a class="navbar-brand" href="#"><img id="imagem-logo-dynatrace" src="images/dynatrace.png" width="30px" height="30px" alt="Logo Principal" title="Logo Dynatrace"></a> </div> <!-- Inicio ul nav com opções das páginas --> <ul class="nav navbar-nav nav-custom"> <li><a href="index.html">Home</a></li> <li class="active"><a href="ambiente-monitorado.html">Ambientes Monitorados</a> <li><a href="arquitetura.html">Arquitetura Dynatrace</a></li> <li><a href="#">Downtime</a></li> <li><a href="#">Indicadores</a></li> <li><a href="como-funciona.html">Licenças</a></li> <li><a href="#">Métricas</a></li> </ul> <!-- Fim ul nav com opções das páginas --> <!-- Inicio ul nav da diretia, com search e login --> <ul class="nav navbar-nav navbar-right nav-custom"> <!-- Icone e botão login --> <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li> <!-- Inicio form do search --> <form class="navbar-form navbar-left" action="/action_page.php"> <div class="input-group"> <!-- Input do search --> <input type="text" class="form-control" placeholder="Search" name="search"> <div class="input-group-btn"> <!-- Botão de submit do search --> <button class="btn btn-default" type="submit"> <!-- Icone do search --> <i class="glyphicon glyphicon-search"></i> </button> </div> <!-- Fim div input-group-btn --> </div> <!-- Fim div input-group --> </form> <!-- Fim form do search --> </ul> <!-- Fim ul nav da diretia, com search e login --> </div> <!-- Fim div container-fluid --> </nav> </div> <!-- Fim do nav fixado no topo--> </header> <div id="div-main"> <div id="div-botoes-pesquisa"> <button class="button-title btn btn-info" id="button-buscar-licencas-ambiente" data-toggle="tooltip" aria-pressed="false"><i class="fas fa-bezier-curve fa-2x" aria-hidden="true" title="Por Ambiente"></i></button> <button class="button-title btn btn-info" id="button-buscar-licencas-servidor"><i class="fas fa-server fa-2x" aria-hidden="true" title="Por Servidor"></i></button><br><br> <input class="form-control mr-sm-2" type="text" id="input-search-host-group" name="filtro" placeholder="Filtrar"> </div> <div id="div-mostra-total-licencas"></div> <div id="div-table-licencas" class="div-table-licencas table-responsive"> <table class="table table-striped table-hover table-bordered" id="table-licencas"> <thead> <tr> <th class="linha-titulo-tabela">Problema</th> <th class="linha-titulo-tabela">Camada Impactada</th> <th class="linha-titulo-tabela">Status</th> <th class="linha-titulo-tabela">Tipo Erro</th> <th class="linha-titulo-tabela">Usuários Impactados</th> </tr> </thead> <tbody id="table-body"> </tbody> </table> </div> <div id="demo"></div> </div> <script src="js/api-get-problems.js"></script> <script src="js/disable-button.js"></script> <script src="js/filtrar-search-licencas.js"></script> </body> <!-- Fim do body --> </html> <!-- Fim do html --> $(document).ready(function() { const Url=''; $("#button-buscar-licencas-ambiente").click(function(){ $.ajax({ url: Url, type:"GET", success: function(result){ console.log(result); var problema = result.problems; var userimpactado = result.problems.impactAnalysis; $.each(problema, function(i, value) { console.log('The value at arr[' + i + '] is: ' + value.displayId); var newRow = $('<tr class="linha-table">'); var cols = ""; cols += '<td class="displayId" id="displayId">' + value.displayId + '</td>'; cols += '<td class="impactLevel" id="impactLevel">' + value.impactLevel + '</td>'; cols += '<td class="status" id="status">' + value.status + '</td>'; cols += '<td class="title" id="title">' + value.title + '</td>'; cols += '<td class="estimatedAffectedUsers" id="estimatedAffectedUsers">' + value.impactAnalysis.impacts.estimatedAffectedUsers + '</td>'; newRow.append(cols); $("#table-licencas").append(newRow); }); }, error:function(error){ console.log('Error ${error}') } }); }); }); Preciso pegar as informações dos campos 
      estimatedAffectedUsers:  numberOfPotentiallyAffectedServiceCalls:    Cada value.displayId pode ter 1 ou mais impactedEntity.   impactAnalysis: {
      impacts: [
      {
      impactType: "SERVICE",
      impactedEntity: {
      entityId: {
      id: "SERVICE-034769111916BA3B",
      type: "SERVICE"
      },
      name: ""
      },
      estimatedAffectedUsers: 0,
      numberOfPotentiallyAffectedServiceCalls: 4496
      },
      {
      impactType: "APPLICATION",
      impactedEntity: {
      entityId: {
      id: "APPLICATION-A8D06FDBBA2EE7F6",
      type: "APPLICATION"
      },
      name: ""
      },
      estimatedAffectedUsers: 2
      },
      {
      impactType: "SERVICE",
      impactedEntity: {
      entityId: {
      id: "SERVICE-B7A98E7FDD81118A",
      type: "SERVICE"
      },
      name: "online-importer-server-v*"
      },
      estimatedAffectedUsers: 0,
      numberOfPotentiallyAffectedServiceCalls: 775
      },
      {
      impactType: "SERVICE",
      impactedEntity: {
      entityId: {
      id: "SERVICE-D773255CD13D8968",
      type: "SERVICE"
      },
      name: ""
      },
      estimatedAffectedUsers: 1,
      numberOfPotentiallyAffectedServiceCalls: 34
      }
      ]  
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.