javascript – ¿Cómo lanzar analytics con una función de js?

Debo lanzar el script de
Google Analytics desde una función de javascript.

Tengo el siguiente código

<script async src=""></script>
    window.dataLayer = window.dataLayer || ();
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-1234567-8', { 'anonymize_ip': true });

¿Cómo puedo escribir el código dentro de una función?

Ya que tal cual o sin la etiqueta script no funciona.

Muchas gracias.

javascript – Find the odd int challange

this is a function given an array of numbers to find the one that appears an odd number of times.

what I did is:

  • Sort the array
  • Check if the array is odd.
  • If the array length is 1 then return this value.
  • Assign every two values to a new array, and check if it is a number.
  • Check if every two values are equals.
  • If not equals then the result will be the first element on the new array
function findOdd(A) {
  let copA = Array.from(A).sort((a, b) => a - b);
  let res = 0;

  if (copA.length % 2 === 0) return;
  if (copA.length == 1) return res = copA(0);
  let newArr = ();
  for (let i in copA) {
    // if not a integer break
    if (!Number.isInteger(copA(i))) {
      res = 0;

    if(newArr.length == 2) {
      const (a,b) = newArr;
      if (a === b) {
        newArr = ();
      } else {
        res = a;
        newArr(0) = b;
    } else if (newArr.length == 1) {
        res = newArr(0);
  return res;

// test the code
findOdd((20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5)); // 5
findOdd((1,1,2,-2,5,2,4,4,-1,-2,5)); // -1
findOdd((20,1,1,2,2,3,3,5,5,4,20,4,5)); // 5
findOdd((10)); // 10
findOdd((1,1,1,1,1,1,10,1,1,1,1)); // 10
findOdd((5,4,3,2,1,5,4,3,2,10,10)); // 1

My code works well, but I looking to improve it.

javascript – Converter JSON em Array

Tenho o seguinte JSON:

let result = {"0":4,"10":4,"30":6,"60":9,"90":12,"120":15,"150":18,"180":21}

Preciso converter em Array no seguinte formato:


Estou tentando da seguinte forma sem sucesso:

let dados = JSON.parse(result)

javascript – Retornar data JSON no HTML

Pessoa, preciso de ajuda com uma chamada de uma API, que retorna um JSON.

Já tentei diversas coisas, mas não consigo fazer com que retorne no meu HTML as informações.

Alguém consegue me apoiar com algum código? Não coloquei aqui o que usei pois utilizei vários.

inserir a descrição da imagem aqui

Só preciso pegar o name e o description. Já usei o name direto, usei, mas nada funcionou.

Um exemplo do meu javascript

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");

btn.addEventListener("click", function() {
  var ourRequest = new XMLHttpRequest();'GET', '');
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
      var ourData = JSON.parse(ourRequest.responseText);
    } else {
      console.log("We connected to the server, but it returned an error.");
  ourRequest.onerror = function() {
    console.log("Connection error");
  if (pageCounter > 10) {
function renderHTML(data) {
  var htmlString = "";

  for (i = 0; i < data.length; i++) {
    htmlString += "<p>" + data.values(i).name + data.values(i).description;

    htmlString += '.</p>';


  animalContainer.insertAdjacentHTML('beforeend', htmlString);
    <h1>JSON and AJAX</h1>
    <button id="btn">Fetch Info for 3 New Animals</button>
  <div id="animal-info"></div>

  <script src=""></script>


javascript – problema al modificar variable global

en esta ocasión vengo por un error bastante simple que me ocurrió, pero que me ha dejado pensativo.
Sucede que tengo una variable normal declarada de forma global, obviamente fuera de la función, y la misma al darle cick a un elemento de mi menú, debe aumentar en 1 su valor. esto la verdad ya lo había hecho antes y la verdad no suponía un problema, pero al repetirlo con esta variable, simplemente no quiere funcionar

function buscar(){
    //buscador de texto
    //let texto=document.getElementById("texto1").value;
    // Obtener solo elementos en contenedor original
    //let texto2=b.getElementsByClassName(texto);

    // Limpia el contenedor, no hay problema

 i2=i2+1; //ya intenté con i2++, i2=+1;
    // Limitas el for con la cantidad de elementos obtenidos
    //for(let num=0; num<texto2.length; num++){
        // Inserta una copia, en lugar del original

if(i2<0){"none"; //i2 se queda en 0 y sigue ejecutando esta parte

Ahora, apliqué eso mismo con el siguiente código y funciona:

function menu2 (){


     //b.setAttribute("style","margin-top:10px;"); //este si funciona

la verdad es algo muy básico pero es que no encuentro diferencia alguna entre ambos códigos; he modificado variables de esta forma antes y ya intentado devolviendo su valor, cambiando el nombre, los símbolos de (<>) por (==, =) y nada. Cabe destacar, todo lo demás, funciones… funciona perfectamente
Muchas gracias por todo

javascript – Como acessar uma função de um componente no onMouseEnter de outro componente – ReactJS

Criei um componente de um cursor personalizado, e tenho uma função nele que altera o tamanho do mesmo.

Queria que, quando o mouse ficasse em cima de outro componente (que no meu caso é um botão), executasse essa tal função de alterar o tamanho do cursor.

<ButtonStyled onMouseEnter={ alterarTamanhoDoCursor }>

javascript – Tracking Ad revenue per page?

I’m trying to look for an ad service that allows me to track revenue per page.

Say a user creates content, a page. The page has an id of 5. On this page, one or more ads are displayed. However, a feature of my website allows users to get a compensation of the ad revenue for creating content (a post).

Are there any web ad services that allow you to track how much revenue is generated on specific page URLs? Or even, a page where I can place some kind of tracking ID in the ad code which I can then reference in my database later?


<!-- A typical post page made by a user -->
<?php $postID = get_post_id();?>
<script src="<?php echo $postID ?>>

<!-- Example Backend to retrieve advertisement stats from a post ID and display it -->
    $postID = 200;
    $adStats = get_ad_stats($postID);
    echo $adStats("revenue") . " ";
    echo $adStats("clicks") . " ";
    echo $adStats("impressions") . " ";

I’m not sure if Google Adsense allows this. Also at the time of writing, their API/documentation appears to be down. Is there any advertising rest API service that allows this?

javascript – Is it possible to programmatically purchase something through a Google Chrome Addon?

I’m new to writing Google Chrome Addons so hopefully the answer to this question is not super obvious.

Is it possible to write a Google Chrome Addon that purchases an item for a user? For example, it would log into the user’s online account, add an item to cart and complete purchase? I’m thinking along the lines of Selenium WebDriver but as a standalone, self executing Chrome Extension.

Obviously, it would be done only with a user’s permission. My question is: does the Chrome Addon tech allows for this possibility? If so, which functions should I be focusing on to start?


How to save the data of an array by prompts and bond with a class in javascript

I am learning poo in javascript for the first time and I am making a program in which by means of prompts the data is stored in an array and then linking that data with a class and being displayed in a message, but I don’t know how to do that the data in the array is bound to the class. If someone could help me with a very basic solution since I don’t know much so far, thank you.

class Libro {

   constructor(titulo, autor, año, genero) {

      this.titulo = titulo
      this.Autor = autor
      this.Año = año
      this.Genero = genero

   informacion() {
      return console.log(`El libro ${this.titulo} del autor ${this.Autor} fue publicado en el año ${this.Año} y es de genero ${this.Genero}`);

let titulo1 = prompt('Introduce el titulo del libro')
let autor1 = prompt('Introduce el autor del libro')
let año1 = prompt('Introduce el año en que fue publicado el libro')
let genero1 = prompt('Introduce el genero literario del libro')

let libro1 = (titulo1, autor1, año1, genero1);

libro1.push(new Libro(titulo, autor, año, genero))


javascript – Layout was forced before the page was fully loaded

I’m testing a Drupal 9 site and it is loading oddly. In development mode in the browser I see the message

“Layout was forced before the page was fully loaded. If stylesheets
are not yet loaded this may cause a flash of unstyled content.

Does anyone know how I get round this? I’m not a developer and am creating this site for a charity, that’s why I have to ask for help.