How to Get the Contextpath from Javascript, the Right Way

How do you get the contextPath from JavaScript, the right way?

Based on the discussion in the comments (particularly from BalusC), it's probably not worth doing anything more complicated than this:

<script>var ctx = "${pageContext.request.contextPath}"</script>

How to define request.getContextPath() as baseUrl in RequireJS config?

Found the answer using JS on another Stack overflow post:

function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}

requirejs.config({
baseUrl: getContextPath() + '/js/ops/libs',
paths:{
jquery:'jQuery-2.2.4/jquery-2.2.4.min',
bootstrap:'Bootstrap-3.3.7/js/bootstrap.min',
dataTables: 'datatables.min',
}
});

get contextpath from javascript

Write this in your page using JSP and refer in js files. It will work.

Make sure you add js file after this code

<script type="text/javascript">

var contextPath='<%=request.getContextPath()%>';

console.log(contextPath);


</script>

and

<input type="button" id="cntButton" value="CONTINUE" 
onclick="javascript:callTest(contextPath+'/test1/test2/test3.do')" />

or pass url and add it in callTest function

<input type="button" id="cntButton" value="CONTINUE" 
onclick="javascript:callTest('/test1/test2/test3.do')" />

main.js

function callTest(pageURL)
{
var url=contextPath+pageURL;
//contextPath will be available, if defined in JSP
}

Fetching a image in server context path from javascript code

You just have to understand how relative paths work. Even if the path is in a JavaScript file, the path is not relative to the location of this JS file, but it's relative to the URL of the HTML page being displayed in the browser.

So, if the URL of the page executing this javascript code is

http://foo.bar.com/myWebApp/zim/boom/tchak.html

and the URL of the image is

../images/icons/search_result.png

The absolute URL of the image will be

http://foo.bar.com/myWebApp/zim/boom/../images/icons/search_result.png 

which is the same as

http://foo.bar.com/myWebApp/zim/images/icons/search_result.png 

An absolute path like /images/icons/search_result.png is also resolved from the root of the web server, and not the root of the webapp (the browser doesn't know what a Java webapp is and doesn't care). So it's resolved as

http://foo.bar.com/images/icons/search_result.png

You would need to prepend the context path to the path to make it really absolute:

<%=request.getContextPath()%>/images/icons/search_result.png

or, without scriptlets:

${pageContext.request.contextPath}/images/icons/search_result.png

How to get context path in plain HTML?

Not sure if this helps you. Try using a CDN:

<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>

It's faster, secure and doesn't need to be downloaded too. Also, you can use relative paths from the domain name, say:

<script
src="/assets/external/jquery-3.3.1.min.js"></script>

The above works if you know where exactly the script resides.

Get rid of hard-coding the context path of web apps in external JavaScript files

What happens is that the included JavaScript file named websockets.js where the global variable contextPath is attempted to be accessed, is placed before the hard-coded <script> tag in the generated HTML <head> tag in the master template

This is unexpected. You declared the <h:outputScript> referring websockets.js file inside <h:body> with target="head". This is supposed to end up after all other script resources already declared in <h:head>. See also a.o. How to reference CSS / JS / image resource in Facelets template? After all, this appears to be caused by PrimeFaces bundled HeadRenderer which is intented to auto-include some CSS resources and take care of the <facet name="first|middle|last">.

This is worth an issue report to PF guys (if not already done). In the meanwhile, your best bet is to turn off it by explicitly registering the JSF implementation's own HeadRenderer back as below in faces-config.xml (provided that you're using Mojarra).

<render-kit>
<renderer>
<component-family>javax.faces.Output</component-family>
<renderer-type>javax.faces.Head</renderer-type>
<renderer-class>com.sun.faces.renderkit.html_basic.HeadRenderer</renderer-class>
</renderer>
</render-kit>

And explicitly include the PrimeFaces theme-specific theme.css as below in <h:head>:

<h:outputStylesheet library="primefaces-aristo" name="theme.css" />

Coming back to the real question,

Anyway, how to get rid of hard-coding the context path in external JavaScript files?

Either set it as base URI (note: relative path isn't supported in HTML4 / IE6-8).

<h:head>
<base href="#{request.contextPath}/" />
...
</h:head>
var baseURI = $("base").attr("href");

Or set it as data attribute of HTML root element.

<!DOCTYPE html>
<html lang="en" data-baseuri="#{request.contextPath}/" ...>
...
</html>
var baseURI = $("html").data("baseuri");

Unrelated to the concrete problem, as a word of advice, to transparently cover both http+ws and https+wss, consider using location.protocol instead of a hardcoded wss.

var ws = new WebSocket(location.protocol.replace("http", "ws") + "//" + location.host + baseURI + "Push");

How to set context path to a variable in javascript

Use

var contextPath = "<%=request.getContextPath()%>"; 

for setting context path in a jsp page.And contextPath should be a global javascript variable.



Related Topics



Leave a reply



Submit