开发者

How to access the text of a remotely loaded "<script>" element?

开发者 https://www.devze.com 2023-01-05 01:14 出处:网络
Well i am currently trying to write an ajax enabled Manga reader application for onemanga using greasemonkey (more precisely js / jquery)

Well i am currently trying to write an ajax enabled Manga reader application for onemanga using greasemonkey (more precisely js / jquery)

my problem is that i need to execute one of the inline scripts on their page to update the next page url. so what i attempted was the following:

$.get(nextPage,function(nxtHtm) // the variable nextPage already contains required url
{
  nxtImgUrl = $(nxtHtm).find(".one-page img").attr("src");   // get next image url
  $("body").append("<img id='dynamic' src='"+nxtImgUrl+"'/>");  // append next image
  $(nxtHtm).find("script:last-1").appendTo("body"); // attempt to a开发者_开发问答ppend script to body
  alert(nextPage); // testing if script to change page url has been executed
});

Howerver that only seems to work on the image part. the script has no effect whatsoever. i also tried to do an alert($(nxtHtm).find("script:last-1").html()); and variants such as .text() or . val() the .html() returns nothing (not "null", it just alerts a blank value) and the other two return null or undefined

Does anyone have an idea of how i can append the remote script here? or alternatively capture the text in between the tags and just eval() it?

thanks ^^


JQuery will ignore the contents of some elements (e.g. <head>), probably in the name of performance. I suspect <script> is one of those.

The solution would be to prevent JQuery from parsing the DOM until you've had a chance to override that behaviour.

  1. Override JQuery default parsing behaviour with a converters block
  2. Replace any <script> tags with <div data-tag="script"> so that they're not ignored
  3. Find the text() of the appropriate div.

Try something like this:

$.ajax(nextPage,{
    success: function( data, status, xhr ){
        data = data.replace(/\<script[^>]+\>/ig,"<div data-script='true'>")
        data = data.replace("</script>","</div>")
        var $data = $(data);
        nxtImgUrl = $data.find(".one-page img").attr("src");
        $("body").append("<img id='dynamic' src='"+nxtImgUrl+"'/>");
        $data.find("div[data-script=true]:last-1").text().appendTo("body");
        alert(nextPage);
    },
    converters:{
        "* text": window.String,
        "text html": true,
        "text xml": true
    },
    dataType:'html'
});

It's possible that you'll hit encoding problems due to invalid entities like &, in which case you may need a RegExp based approach, which is also possible. Let me know how you get on.


search for jsonP or comet programming.

0

精彩评论

暂无评论...
验证码 换一张
取 消