3

Eu possuo esse script. O que eu devo acrescentar nele para que, ao ser executado, apareça em uma <div>?

Aqui está o script:

// Which flash versions are needed for given format
var FLASH_VERSIONS = {
    '7/0/0': [5],
    '9/0/115': [18, 22, 33, 34, 35, 37, 38, 59, 78, 82, 83, 84, 85, 120, 121],
    '10/1/0': [52, 53, 54, 60],
    };

// Regex to extract the video format
var RE_ITAG = /&itag=([0-9]*)&/i;

function get_fmt(content) {
    var fmt = new Object();
    fmt.list = new Array();
    fmt.stream_map = new Array();

    for (var i=0; i < content.length; i++) {
        var url = content[i]['url'];
        if (url.search("") == -1)
            continue;

        var matches = RE_ITAG.exec(url);
        var itag = matches[1];

        var resolution = '7/0/0';
        for (var possible_resolution in FLASH_VERSIONS.length) {
            if (FLASH_VERSIONS[possible_resolution].indexOf(itag)) {
                resolution = possible_resolution;
            }
        }

        fmt.list.push(itag+'/'+String(content[i].width)+'x'+String(content[i].height)+'/'+resolution);
        fmt.stream_map.push(itag+'|'+content[i].url.replace(/,/g, '%2C'));
    }

    fmt.list.reverse();
    fmt.stream_map.reverse();
    return fmt;
}

function get_embed(content) {
    var fmt = get_fmt(content);
    var flashvars = new Array();
    flashvars.push('fs=1');
    flashvars.push('hl=en');
    flashvars.push('autoplay=1');
    flashvars.push('ps=');
    flashvars.push('playerapiid=uniquePlayerId');
    flashvars.push('fmt_list='+encodeURIComponent(fmt.list.join()));
    flashvars.push('fmt_stream_map='+encodeURIComponent(fmt.stream_map.join()));
    flashvars.push('');
    flashvars.push('t=1');
    flashvars.push('vq=large');
    flashvars.push('auth_timeout=86400000000');

    var embed = document.createElement('');
    embed.setAttribute("src", "");
    embed.setAttribute("type", "application/x-shockwave-flash");
    embed.setAttribute("allowfullscreen", "true");
    embed.setAttribute("allowscriptaccess", "always");
    embed.setAttribute("scale", "noScale");
    embed.setAttribute("wmode", "opaque");
    embed.setAttribute("flashvars", flashvars.join("&"));
    embed.setAttribute("width", "100%");
    embed.setAttribute("height", "100%");
    return embed;
}

var ts = Math.round((new Date()).getTime() / 1000);
var script = document.createElement('script');
var hash = document.location.hash;
var id = hash.substr(1,hash.length);
var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');

script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'https://');
head.appendChild(script);

myFunction(); // Fails because it hasn't loaded from my.js yet.    
    window.onload = function() {
        // Works most of the time but not all of the time.
        // Especially if my.js injects another script that contains myFunction().
        myFunction();
    };

Como faço para ele ao ser carregado numa pagina html apareça dentro da div especifica?

Exemplo:

<div id="script" class="#">/div>
4
  • Uma duvida... o que tem na váriavel ts? 18/08/2014 às 16:45
  • Se refere a essa parte Math.round(ts/3600 ? ali ira aparece uma embed
    – Endou
    18/08/2014 às 17:03
  • Retirei aquela parte. ela não era para esta ali
    – Endou
    18/08/2014 às 17:09
  • Como já te disseram aqui (aliás, é a mesma pergunta, não?), não existe isso de "o script aparecer dentro de uma div". Depende do que o script faz. Ele pode escrever conteúdo em algum lugar ou não. Qual é o script que você está tentando executar? Pegando esse seu exemplo, qual seria o conteúdo de myFunction?
    – bfavaretto
    18/08/2014 às 19:20

2 Respostas 2

5

Remova esta parte do script, ela é desnecessária:

myFunction(); // Fails because it hasn't loaded from my.js yet.

window.onload = function() {
    // Works most of the time but not all of the time.
    // Especially if my.js injects another script that contains myFunction().
    myFunction();
};

Agora repare nesta linha:

script.setAttribute('src', 'https://?authuser=0&alt=jsonm&urlredir=1&commentreason=1&fd=shapes&thumbsize=d&max-results=100&callback=picasa_callback&t=');

Em particular, nisto aqui:

callback=picasa_callback

Quando o script for inserido, a função indicada como callback será chamada. Neste caso, é a função picasa_callback. Agora veja como ela é:

function picasa_callback(obj) {
    document.body.appendChild(get_embed(obj['feed']['media']['content']));
}

Ela pega um HTML (gerado por get_embed) e insere no final do <body>, com document.body.appendChild. Se você quer inserir esse HTML na sua div com id script, faça o append nela e não no body:

function picasa_callback(obj) {
    document.getElementById('script').appendChild(get_embed(obj['feed']['media']['content']));
}

Importante: para garantir que a div exista quando o callback for chamado, inclua seu script no final do HTML. Certifique-se que o script esteja depois do <div id="script" class="#"></div> no código-fonte.

7
  • Mas nesse caso o user vai fica exposto no html?
    – Endou
    18/08/2014 às 19:55
  • Sim, você não tem como evitar isso. No HTML (opção "exibir código fonte") ele não vai aparecer porque foi injetado, mas qualquer inspetor de código será capaz de ver essa url.
    – bfavaretto
    18/08/2014 às 19:56
  • Seria possivel troca a id do user apenas pela div? tipo '+id+'
    – Endou
    18/08/2014 às 20:03
  • Não entendi ...
    – bfavaretto
    18/08/2014 às 20:05
  • Digo ao inves de usa o script em varios lugares, usaria o mesmo script, apenas alterando pela div o user ou o video carregado
    – Endou
    18/08/2014 às 20:12
1

Eu sugiro usar a biblioteca JQuery pro mater compatibilidade com diversos navegadorse e pode usar o código:

link para incluir a lib:

<script src ="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Código Javascript:

$(function() {
  $('#script').append('<div></div>');
});

Pode dar uma olhada no JS Fiddle: http://jsfiddle.net/L1ufwdt9/4/

7
  • Da para fazer apenas com java?
    – Endou
    18/08/2014 às 17:33
  • Você quer dizer Javascript? Não tem porque, dá sim, vou modificar lá no JS Fiddle.
    – Luiz Rossi
    18/08/2014 às 17:35
  • Assim, na verdade dá, mas não é cross-browser e se você utilizar mais de uma imagem, ou iFrame na página, ele vai carregar diversas vezes. stackoverflow.com/questions/595808/…
    – Luiz Rossi
    18/08/2014 às 17:43
  • O codigo não funciona, aparece apenas a letra que você adicionou ali
    – Endou
    18/08/2014 às 17:51
  • Acho que não entendi sua pergunta então, o que você quer adicionar dentro da div? eu adicionei uma outra div com o conteúdo 'b'
    – Luiz Rossi
    18/08/2014 às 17:56

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .