Change page title with js - javascript

I'm using some Ajax/other code (from https://jesse.sh/rethinks-dynamic-page-replacing-content/) to load partial page content into a specific div.
As it doesn't grab the title of the new content, the page title unhelpfully remains that of the initially-loaded page.
Unable to find a solution which handles the title appropriately, I'm using a kludge of 'console.log(href);' with 'document.title = location.href.replace ()' to produce an url-based title, from which are then removed the http:// and various other things before the page title.
It seems to work, but requires me to think about just what needs to be removed and chain accordingly.
In the absence of some code which replaces the title accordingly and thus doesn't require the above kludge, I'd like to be able to use a single unchained 'replace' which removes everything before the page title.
However, I don't understand enough to be able to do so.
Suggestions appreciated - please/thanks/etcetera.

Use document.title.
For example
document.title='your title';

Related

Dynamically loading content on local HTML page [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Context:
Basically I'm attaching a little HTML help doc to go with my program (not meant to be on a server, viewed locally). HTML just because I'm most comfortable in making docs in it but I also want it to have some interactivity/dynamic content which I can't do in a PDF or whatever.
I'm dynamically replacing the content when you click on a link instead of making every page need it's own HTML page, which is just something I'm used to doing so I can change the menu and banner and whatever else on a single 'main' html file without having to adjust every single other html file for one tiny change in the shared stuff.
Current Method:
Right now it's all done through javascript and jQuery. When a user clicks a link, I use jQuery's load() function to load the appropriate content (an html file) and replace the content div with what's in the loaded html file. Currently just using relative links. E.g. the core function is something like below:
$("#ContentBox").load("content/faq.html");
This actually worked a few weeks ago when I first wrote it. It's not like I built the whole thing and didn't test its core concept until just now. But now it seems all the browsers are blocking it. Chrome says:
XMLHttpRequest cannot load file:///C:/[....]/content/home.html. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource. `
Question:
So I understand why it's happening as it's a potential security risk to allow that, I just want to figure a good way around it that still does what I want (if it's possible). I mean I could just preload all the content as huge string variables in the javascript file or as hidden divs that get turned on and off, but I was hoping for something a little more elegant.
And I can't expect all users of my program to setup a local web server just to view to help doc.
I've considered the File and FileReader classes but they require a user input for a lot of functions. There's also iFrames but that introduces all sorts of weirdness that needs to be accounted for and I hate iFrames.
If this is all local content then you should not be loading it via ajax. One option you have at your disposal is to set up your help files as local Javascript templates. You can then refer to them using a template library like mustache or underscore and link to them in your application like so:
<script type="text/template" src="local/helpfile.js" />
If you don't want to use a templating library then you can set up helpfile.js as JSON data, but you'll need to escape quote characters first.
If your help docs are to be viewed on a Windows machine only, you should look into using HTML Applications to get rid of the cross-origin issues. Or you can work around it by combining all of the source code files in hidden textareas. I've done it lol
To anyone still interested this is the solution I settled on as of now. At the end of the body are all the divs with the different page content styled like so:
<div id='PageName' class='content-div'>
<!-- content goes here -->
</div>
<div id='AnotherPage' class='content-div'>
<!-- content goes here -->
</div>
The id is important as that becomes the name of the page and the class type, which you can name whatever, I used to hide them with visibility:hidden; as well as gave it absolute positioning at 0,0 - just in case - so that they don't interact with other elements and screw up the layout.
On the page loading, along with a bunch of other functions, I store the elements into a javascript associative object by page name.
var content = {};
function onLoadThisGetsCalledSomewhere() {
// loop through all of those divs
$(".div-content").each(
function() {
// using $(this) to grab the div in the scope of the function here
var element = $(this).element;
var name = $(this).attr('id');
// remove it from the html (now it exists only in the content object)
element.detach();
// remove that style class that makes it invisible
element.removeClass('content-div');
// put it into memory
content[name] = element;
}
);
}
So when a link to another page is clicked, the onclick does something like switchPage(pageName) let's say.
function switchPage(requestedPage) :
// somewhat simplified, real version has case and null checks that take you to 404 page
var contentElement = content[requestedPage];
// replace content in some container div where you want content to go
$("#TheContentContainer").empty().append( contentElement );
// have to adjust size (width possibly too but I had a fixed width)
$("#TheContentContainer").height( contentElement.height() );
}
I'm not at the same computer so I'm writing all this up anew, not copy/pasting so there may be some bugs/typos (Caveat emptor - I'll fix it tomorrow). The version I used is somewhat more complicated as well since I have subpages as well as dynamically handled menu bar changes. Also features so that you can open the "links" correctly in new windows/tabs if such an action is made. But that's not important here now.
It's not too different I suppose with hidden divs (the benefit here is the detach() function to remove it from the html) or just storing long strings of html code in java vars (much more readable than that though), but I think it's advantage is is much cleaner (IMHO) and so far I like it. The one downside is with lots of pages you get one huge HTML doc that can be a pain to go through to edit one specific page but any decent editor should have a bookmark feature to make it a little easier to get to the line you're looking for. Also cause of that a bad idea if not local, but then again if it's online just use the jQuery load() function.

JSP/Javascript: How to dynamically change a header based on the page im on

I have a header.jsp file that is included in all my pages on the website what acts as a template for all my header content (e.g site titles, logos, home links etc.). Inside this header.jsp I want to set up a page title in a h1 tag (for example) that would change to show the title of whatever page I am on when navigating through the pages of the website.
My initial thought was to use javascript to achieve this however based on the tutorials, most people are using frameworks like angular which I dont really want to resort to using unless there was no alternative. Is there any way I can change my headers to pick up whatever page I am on using raw JavaScript? Or, is there anything in jsp that can also make this possible? If so how can I achieve this?
How about setting the page title as a request attribute page_title and then fetching it in your header.jsp.
Thank you for the responses. I have managed to figure out one alternative that has worked for me though I wouldnt say it is the most graceful. (Any suggestions to improve this and I will update my answer for better understanding!) Also worth noting the solution was using jsp NOT javascript.
What I have done is within my header.jsp, I had set up in the body the following code between a div tag:
<%= subTitle %>
From there, I then applied the following code to all other pages on my website:
<% String subTitle="Example Page"; %>
'Example page' being the name of the webpage that I want to show on my header but it can be different on any page and had given me the expected results.
The only thing is however that in doing it this way, when it is set on Eclipse Luna I get a problem where 'subTitle cannot be resolved to a variable'. The code in itself works but it is problems like these that I would also rather resolve in order to provide the best solution. Any suggestions to remove this error would be appreciated.

DOJO and DIJIT can not parse same ID twice?

I am having a problem while working with DOJO where I will dynamically load a div with some content and then run parser.parse(dom.byId("mainDiv")); with the respective requires. And that works beautifully the first time. The second time however I end up running into a problem where it just shows the content no longer activated or styled.
On a second run what I do is remove all the html in the div and then replace the html with basic unparsed text and then I parse it again. Now I am guessing it has to do something with dijit.registry however I can not find exactly what the issue is as I have tried clearing that out as well to no avail. Your help would be much appreciated.
Dojo keeps track of the objects / widgets it creates by the specified id. If you run the parser again on an object with the same id, dojo tries to create a second instance, but there is already one, so it should throw an error in your js console (please check).
You could leave the id blank, then dojo / parse should create an id for you.
Dojo allows you to find dom elements by class attributes, that way you could pass your div-element to the parse() function without giving it an explicit id.
Anotherway would be to destroy the created widget/object before you parse the div-element again, take a look here for that:
Dojo and unregistering widgets
Quote from http://livedocs.dojotoolkit.org/dojo/parser#parse
"If you try to parse the same content twice, or parse content
mentioning id's of existing widgets, it will cause an exception about
duplicate id's"

How to use page-mod to modify element loaded by JavaScript

I'm creating firefox addon to add onclick event to the specific button. ("input" element)
The button is placed in http://example.com/welcome#_pg=compose
but when I open the page, following error occures:
TypeError: document.querySelector("#send_top") is null
#send_top is id of the button which I want to modify. So, the button is not found.
This error occurs because http://example.com/welcome and http://example.com/welcome#_pg=compose is completely different pages.
In this case, the addon seems loading http://example.com/welcome but there is no button whose '#send_top' ID.
When #_pg=compose anchor is added, the button is loaded by JavaScript.
How can I load http://example.com/welcome#_pg=compose to modify the button?
Three thoughts to help you debug this:
to correctly match the url you should consider using a regular expression instead of the page-match syntax - this might allow you to react to the anchors in a more predictable way
I've found that when using content scripts with pages that are heavily modified by JS, you can run into timing issues. A hacky workaround might be to look for the element you want and, if it isn' there, do a setTimeout for a 100 milliseconds or so and then re-check. Ugly, yes, but it worked for some example code I used with the new twitter UI, for example.
You can use the unsafeWindow variable in your content script to directly access the page's window object - this object will contain any changes JS has made to the page and is not proxied. You should use unsafeWindow with great caution however as its use represent a possible security problem. In particular, you should never trust any data coming from unsafeWindow, ever.

Is it possible for a link not to have an explicit href?

For example I get this as part of a third-party embed code
<a class="cs_import">Add from Address Book</a>
Not surprisingly "Add from Address Book" does not link to anything...but it is allegedly supposed to. How is this possible and if it is possible for this to be a link..what could be the reason my link is broken?
Yes. It is possible.
Why would someone do it?
Is is being used as a fragment anchor. This is not the case in your example because there is no name attribute. But if it had a name="myfragment" and the page file name was page.html, then page.html#fragment would automatically scroll the browser to that point on the page.
It is being used only for styling purposes. This could be a reason for doing it, but it is not a good reason, because styling can be accomplished either way.
It is being assigned an href attribute programmatically with javascript. For example, I could have a script that selects all the a tags with a specific class and assigns an href based on the text value, such as $("a.cs_import").attr("href",getHref(this.text()));, where getHref(innerText) is a javascript function that gets the URL from the description text. There is almost always a better way to do things than this, but there are some circumstances that warrant it.
It's possible with JavaScript. One could, upon page load, run some JS code that looks for this element and adds an onClick handler to it.
If the link is supposed to be "enhanced" with some javascript code, the third party probably gave you a javascript file to include as well. Be sure you're including that javascript file, and that you're doing it in the right place according to the vendor's instructions.
href is just an attribute of the link tag. You can leave it out but it wouldn't be very semantic (might not even validate). I know that some browsers just show the element but doesn't allow you to click it.
In your case, maybe the link might be enhanced with JS later on. If it doesn't get enhanced, it's pretty much a glorfied span element.
If an '<a>' element does not have a href attribute it is not focusable, and is not included in the tab order for keyboard access. href='#element' works by appending the hash to the current location, and '#' with no anchor identifier works like an id that is not found on the page, ususally by scrolling to the top of the page unless caught and handled.

Categories

Resources