如何使用javascript获得网站链接

how to get website link using javascript

本文关键字:网站链接 javascript 何使用      更新时间:2023-09-26

我试图获得网站链接,并把它放在一个图像源添加图像路径,例子:假设我在一个网站内部,我想获得它的链接,并将我的图像路径添加到它,并将其注入源图像在同一页面的源代码。

注意:我正在使用SharePoint网站,我们可以用HTML或JavaScript做吗?

您可以从javascript中获得网站地址。使用下面的代码。

window.location.href  : Complete link 
window.location.host : you'll get sub.domain.com:8080 or sub.domain.com:80.
window.location.hostname : you'll get sub.domain.com.
window.location.protocol : you'll get http:
window.location.port : you'll get 8080 or 80.

window.location对象还公开了其他属性。

在所有SharePoint页面上都有一个全局javascript变量_spPageContextInfo。它包含有关当前上下文的基本信息。

根据您的图像是存储在web还是站点收集级别,您应该使用以下其中之一:

_spPageContextInfo.webAbsoluteUrl
_spPageContextInfo.siteAbsoluteUrl

要获得网站的位置,您可以在js中编写以下代码

window.location.href //gives complete href path

将其添加到图像中,可以在HTML中添加图像:

var elem = document.createElement("img");
elem.src = window.location.href+"/my-image.png";
elem.setAttribute("height", "200");
elem.setAttribute("width", "200");
elem.setAttribute("alt", "my image");
document.querySelector("#image-container").appendChild(elem);

更新答案2:

因为它是你想要的基本路径,你可以硬编码它,因为它永远不会改变。

在html中添加一个图像:

var fullPath = window.location.href;
var baseDomain = fullPath.split('site1')[0];
var pngPath = '_catalogs/masterpage/images/banner1.png';
var elem = document.createElement("img");
elem.src = baseDomain + pngPath;
elem.setAttribute("height", "200");
elem.setAttribute("width", "200");
elem.setAttribute("alt", "Banner");
document.querySelector("#banner").appendChild(elem);