window.location.href不会产生确切的url

时间:2015-01-23 04:12:40

标签: javascript

出于某种原因,在我的javascript中,window.location.href只返回域名而不是当前页面地址。

function addLink() {
    console.log('hey');
    var body_element = document.getElementsByTagName('body')[0];

    var selection;
    selection = window.getSelection();

    // added lines begin
    var htmlDiv = document.createElement("div");
    for (var i = 0; i < selection.rangeCount; ++i) {
        htmlDiv.appendChild(selection.getRangeAt(i).cloneContents()); 
    } 
    var selectionHTML = htmlDiv.innerHTML;    
    // added lines end

    var pagelink = "<br /><br />Read more: " + window.location.href + " <br />";
    var copytext = selectionHTML + pagelink; // <------------------- changed line

    var newdiv = document.createElement('div');
    newdiv.style.position='absolute';
    newdiv.style.left='-99999px';
    body_element.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    selection.selectAllChildren(newdiv);
    window.setTimeout(function () {
        body_element.removeChild(newdiv);
    }, 0);
} 
document.oncopy = addLink;

该文件在http://www.chefsuccess.com上有效 谢谢!

1 个答案:

答案 0 :(得分:2)

My script won't work in IE (even 9)? simple javascript to amend copy text

也许您可以在上面的链接上找到答案。

IE需要

document.body.oncopy=copyCopyright

添加到您的onload事件中。 (身体在装载之前不存在)