开发者

Display current URL of webpage (dynamic) in HTML

I have this code in my HTML:

<h3 id="left">Lorem Ipsum </h3>

                <h3 id="right">[Current URL Here]</h3>

I want to display (dynamicly) the current URL inside the <h3> tags. I'开发者_如何转开发ve been trying to figure it out for a few days, but I'm really a mobile developer, not an HTML developer, so it's proven difficult. I need this for an app I'm working on, so Please go easy on me :)

Thanks in advance.


document.getElementById('right').innerHTML = window.location.href;


If you wanted to do it in PHP, it's a little more involved:

$url = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['HTTP_HOST'] . htmlspecialchars($_SERVER['REQUEST_URI']);

As aronasterling points out, you need to sanitize $_SERVER['REQUEST_URI'] to prevent XSS.


Well, you simply cannot do it in pure HTML.

With javascript, you can go with

<h3 id="right">
<script type="text/javascript">
document.write(location.href);
</script>
</h3>

Otherwise, if you are requesting a page on the server, you should rather have it done in there.


the php code for getting complete url of current page is as follows

<?php 

    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';

    echo $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>

Reference

if you want to use javascript use the method suggested by @MooGoo

full usage of that script is as follows

<SCRIPT LANGUAGE="JavaScript">        
   document.getElementById('right').innerHTML = window.location.href;       
</SCRIPT>

use this after you declared/defined <h3 id="right">[Current URL Here]</h3>

Hope helpful


<script type="text/javascript">
var segments = window.location.pathname.split('/');
var toDelete = [];
for (var i = 0; i < segments.length; i++) {
    if (segments[i].length < 1) {
        toDelete.push(i);
    }
}
for (var i = 0; i < toDelete.length; i++) {
    segments.splice(i, 1);
}
var filename = segments[segments.length - 1];
console.log(filename);
document.write(filename);
</script>


While the JavaScript are what is more common, you could also use Server-Side Includes:

<h3 id="right">
    <!--#echo var="SERVER_NAME" -->/<!--#echo var="DOCUMENT_URI" -->
</h3>
  • instead of SERVER_NAME you can try HTTP_HOST
  • instead of DOCUMENT_URI you can try REQUEST_URI; one includes the query string, the other doesn't


Php Code:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

<h3 id="right">echo curPageURL();</h3>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜