JavaScript function "if there is url in document"

Discussion in 'JavaScript' started by Sordello, May 3, 2009.

  1. #1
    Hi,

    I need a JavaScript function tha does that:

    * Verify if there is an URL in document
    * If there is so ok.
    * If not shows an alert.

    Can anyone help me?
     
    Sordello, May 3, 2009 IP
  2. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    If you mean within the current document something like this:
    
    <script type="text/javascript">
    window.onload = function() {
        if(document.body.innerHTML.search("http://www.yahoo.com") == -1) window.alert("URL Could not be found in document.");
    }
    </script>
    
    Code (markup):
    You have to make sure that the script is inserted BEFORE the <body> tag of the document....
     
    camjohnson95, May 3, 2009 IP
  3. Sordello

    Sordello Peon

    Messages:
    27
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi Camjohnson95,

    I tried adding code before <body> and it worked perfectly.

    But there is any way to work inside <body> tag?

    Regards and thank you very much,

    Diego
     
    Sordello, May 3, 2009 IP
  4. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #4
    ok,
    The reason that it needs to be before the body tag is because otherwise it picks up the string from the script and always return true... so if we join two parts of the url to make one it will work fine from anywhere:

    
    <script type="text/javascript">
    var strUrl;
    window.onload = function() {
        strUrl = "http://".concat("www.yahoo.com");
        if(document.body.innerHTML.search(strUrl) == -1) window.alert("URL Could not be found in document.");
    }
    </script>
    
    Code (markup):
     
    camjohnson95, May 4, 2009 IP