I am trying to retrieve the title of a URL for a link.
For example get the title of this:
<a class="stack" href="http://stackoverflow.com" title="Stack Overflow">
will be generated dynamically from something like this: $('.stack').attr("title", "....");.
Is that possible with javascript or jQuery to retrieve the title of a URL?
Thanks alot
Took a little time to make, but this example allows you download a web page from your web page. Then extract the title from the title tags.
<html>
<head>
<!-- jQuery include -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- This include allows cross domain get requests -->
<script type="text/javascript" src="https://raw.github.com/jamespadolsey/jQuery-Plugins/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<!-- Sample -->
<script type="text/javascript">
$(document).ready(function(){
//gets the href of the first anchor
var url = $("a").first().attr("href");
//sets a get request to get the html source
$.get(url, function(data){
//uses get string between function to get the text between the title tags
//then calls it in a message box
alert(getStringBetween(data.responseText, "<title>", "</title>"));
});
});
function getStringBetween(input, start, end){
var index = input.indexOf(start);
if(index != -1){
index += start.length;
var endIndex = input.indexOf(end, index + 1);
if(endIndex != -1)
return input.substr(index, endIndex - index);
}
return false;
}
</script>
</head>
<body>
Google
</body>
</html>
Yep, just use document.title. Simple and effective.
$('.stack').attr("title", document.title);
EDIT: It looks like I misunderstood your question. If you want to get the title of another page, not the currently loaded page, you could do some cross-domain AJAX trickery, but it's not generally a good idea. I'd just grab the page title server side (in whatever you are using to generate the page [php, asp, etc]) and output it.
For security reasons, you cannot read content from a different website using Javascript, even just to read the title.
You could write a server-side proxy that requests a remote page and finds its <title> tag using an HTML parser.
However, you shouldn't do this at the client side; it will waste time and resources.
If you really want to do this, do it once on the server as a pre-processing step when you create a new page.
Unless the URL's href is on the domain of the current document, using JavaScript to try to get the title of the target document would require cross-domain scripting which is not generally allowed (using traditional methods) by browsers. Unless you're real fancy with proxies (not entirely sure how that is done), you'll need a server-side language to load the document first.
Related
As the title reads, I want to import an HTML-file as external CSS to a website.
Just hear me out: my problem is that I'm working with a very inconvenient CMS that doesn't let me upload CSS-files no matter what.
I'm able to write CSS inside the page directly via HTML-style-tag but that generates a lot of text on every site and also makes maintaining CSS tedious.
As I can't upload CSS-files, I thought maybe I can create a dummy-site inside the CMS with only CSS in it and then later import that site as CSS.
The idea was: when parsed, the HTML of the site (header, body, etc.) will just be skipped (as when CSS has i.e. type-errors) while any valid CSS found is going to be imported.
Now when I try importing this website with
<style type="text/css"> #import url(dummyCSSWebsiteURL); </style>
(as the CMS also doesn't grant me access to the header of a page),
I - of course - get the error:
"Resource interpreted as Stylesheet but transferred with MIME type text/html"
as I am obviously requesting an HTML-file and not CSS.
I also tried jQuery to simply include all the dummy-HTML into an element (that I would have just not displayed):
$("#cssDummy").load(dummyCSSWebsiteURL);
but I get 2 errors that are probably just showing what a horribly inefficient idea this is:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience
A parser-blocking, cross site (i.e. different eTLD+1) script, ["..."], is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load, it will be confirmed in a subsequent console message.
maybe I am just disregarding (or not understanding) things on a conceptual level at all but I still wonder if there is a workaround for this problem?
EDIT: I found a workaround
Definitely don't recommend. Try using different server as pointed out in the comments if you can.
I used an XMLHttpRequest to get the external site's HTML, then used regEx to match the content of the div on the page that contains the css and - with added style-tags - inserted the matched css into a div on the page.
Code for external site that contains the CSS:
<div id="generalCode">.testBox{background-color: red; min-height: 200px;}</div>
Code on site that imports the external CSS:
<div class="testBox">
</div>
<div id="cssCodeOnPage">
</div>
<script>
// use onload if you want
getCssCode();
function getCssCode(){
// send request to page where div #generalCode contains css
var xhr = new XMLHttpRequest();
xhr.open('GET', dummyCSSWebsiteURL);
xhr.onload = function(){
// use regex to separate css from rest of html
var re = /<div id="generalCode">([\s\S]*?)<\/div>/;
var cssString = xhr.response.match(re)[1];
cssString = "<style>" + cssString +"</style>";
// insert css into div
var cssDivOnPage = document.getElementById('cssCodeOnPage');
cssDivOnPage.innerHTML = cssString;
}
xhr.send();
}
(sorry for this monstrosity of a question..)
I think the best option is to load that HTML page into an iframe, query the styles out of hte iframe, and then attach that to the current document. I created a live example on Glitch here.
Nothing but the <style> block will be copied from the HTML. The external HTML document does need to be an actual HTML document though (<html><head><style>....), otherwise the page won't be queryable to retrieve the CSS.
This is an example in plain JavaScript:
// Create an iframe
const iframe = document.createElement("iframe");
// Make it not visible
iframe.style.visibility = "hidden";
// This will run once the HTML page has loaded in the <iframe>
iframe.onload = () => {
// Find the <style> element in the HTML document
const style = iframe.contentDocument.querySelector("style");
// Take that <style> element and append it to the current document's <head>
document.querySelector("head").appendChild(style);
// Remove the <iframe> after we are done.
iframe.parentElement.removeChild(iframe);
};
// Setting a source starts the loading process
iframe.src = "css.html";
// The <iframe> doesn't actually load until it is appended to a document
document.querySelector("body").appendChild(iframe);
Its possible in a different way. However not through JS, but PHP include
For that however, your server needs to support PHP and need to use PHP instead of HTML as documents. Sounds more complicated now then it actually is. To use PHP the document has to becalled .php at the end instead of .html e.g. index.php.
The document itself can be written the very same way as you write HTML websites.
Now for the issue to use PHP include. you inlcude the CSS as head style:
index.php:
<html>
<head>
<?php
include('styles.css');
?>
</head>
<body>
content
</body>
</html>
the line <?php include('url'); ?> will load a file mentioned in the url server sided into the document. Therefor you only need to create another file with the name styles.css and write your css in there the normal way.
You Do
<link rel="stylesheet" href="css/style.css">
I have a webpage uses object that are external websites (or other web pages).
for example:
<object data="external.html"></object>
on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.
For example, when using:
<object data="www.google.com"></object>
If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.
Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.
You can collect current URL using location.href and then collect object using its ID and then append data as current URL to it.
This should not possible as it will violate cross domain security policies. The same restriction is there with iframe, so I guess it applies to object as well.
If it is same domain, you can try getting the current URL from contentWindow or contentDocument
<objectElement>.contentWindow.location.href
Hope this is what you are looking for. You can split the url.
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>
I'm looking to solve the issue of not being able to Save/Apply changes to an .html document when the document.createElement("div"); is used in JavaScript. I want to be able to save the changes made to the document and 'overwrite' the original .html document.
Future Possibilities(these can be ignored):
Deletion of these elements, and saving those changes as well to revert it back to it's original state.
EDIT: --------------
I didn't make this clear, sorry!
THIS CODE IS TO EMBED MULTIPLE YOUTUBE VIDEOS ON A SINGLE PAGE; I WOULD LIKE SOME HELP HAVING SOMETHING OVERWRITE THE ORIGINAL .HTML DOCUMENT. THEREFORE LOADING THIS NEW CONTENT EACH TIME SOMEONE OPENS THE PAGE.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
</div>
<script>
function myFunction() {
var parentElement = document.getElementById('parentElement');
var theFirstChild = parentElement.firstChild;
var newElement = document.createElement("div");
parentElement.insertBefore(newElement, theFirstChild);
newElement.setAttribute("id", "newElement");
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
}
}
</script>
</body>
</html>
I think what you're asking is how to put dynamic content in a static web page. This is not my area of expertise, but I can give you the outlines of how to do what you're trying to do. This is the architecture. You'll have to fill in some implementation details yourself, but I'll try to give you a clear idea of what you'll be googling for at each step of the way.
Suggestions for improvement from real web guys will be eagerly embraced. If there's already an answer on SO that walks a noob through the design of a trivial single-page AJAX/JSON web app, I can't find it. There must be one, though.
This is a lot more complicated than your original idea, but rewriting a web page not a great idea: You're writing arbitrary zeroes and ones from strangers to a file on your server. You need one HTML file per user, if you store their data in HTML files. How do you serve him the right one? What if you change the layout after you have 500 users? You'd be writing a script to alter the text of 500 HTML files. In practice it's just a horrorshow.
What you're groping for is dynamic content via AJAJ, which we usually still call AJAX for historical reasons (prior to the advent of CNC machining, curly braces were difficult to mass produce economically, and so web services commonly used pointy brackets instead).
First, write a web page to serve the user's personal content. It'll save updates as well. May as well use PHP. That "page" isn't a web page; instead of HTML, it returns JSON text with a content-type of application/json. The user can POST text to it in JSON format as well. This "page" is a web service.
On a get request, the web service page, given a username (and appropriate security), will retrieve the user's YouTube video list from MySQL and return it to the caller as JSON.
For now, the content going to and from that web service page is pretty simple. Just a list of URLs. Let's make it an object that has one member, and that one member will be an array of objects that contain information about YouTube videos the user has chosen. For now, each one just has a URL, but we may want to add more detail later, so we won't just make it an array of bare URL strings. At the top level, we'll also be able to add other types of content alongside "YouTubeVideos" if there's a need -- for example, you're going to want a username and a security token.
{
"YouTubeVideos": [
{
"url": "http://youtu.be/LKJDFKLJDF"
},
{
"url": "http://youtu.be/87sdfd234"
}
]
}
In the HTML page, your JS code will first request the user's data from that web service in onLoad. You'll do that using XMLHttpRequest. You'll use the JavaScript function JSON.parse to turn the response text into a JS object.
So write a function called requestUserYTContent or something, and call that from onLoad. This is simplified: There's no validation, exception handling, etc.
// Empty default instance to start out.
var ytInfo = { "YouTubeVideos" : [] };
function requestUserYTContent() {
// ...
// Do stuff with XMLHttpRequest to get the JSON for this user from
// the web service.
// ...
ytInfo = JSON.parse(http_request.responseText);
console.log('Got ' + ytInfo.YouTubeVideo.length + ' videos');
// Once you've got that JSON object, you can loop through the
// videos and do stuff with their urls. We'll stick that loop in
// another function so we can re-use it in cases where the list
// changes for reasons other than a web service call.
var ytDiv = document.getElementById('ytContent');
ytDiv.innerHTML =
generateVidListHTML(ytInfo.YouTubeVideos);
}
function generateVidListHTML(vids) {
var newHTML = '';
for (var i = 0; i < vids.length; ++i) {
var url = vids.YouTubeVideos[i].url;
// ...generate HTML to display this video, and append to
// newHTML
}
return newHTML;
}
So we keep that ytInfo around in a global variable. When the user adds to the list or deletes from it, alter the list, re-generate the HTML with generateVidListHTML(), insert the HTML into the page as above, and then post the newly-altered list as JSON back to the web server to update the user's content in the mySQL database.
You'll POST data back to the web service with XMLHttpRequest. Here's an example. You'd be using a different content-type, of course.
https://stackoverflow.com/a/9713078/424129
In JavaScript in the web page, converting a live JavaScript object back to JSON is easy: https://stackoverflow.com/a/4162803/424129
For simplicity, you may as well just pass the same JSON format back and forth.
When you send JSON back to the web service, it'll need to parse it too. I don't know how to parse JSON in PHP, but I know somebody who does:
https://www.google.com/search?q=how+to+parse+json+in+PHP
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="container">
<div id="header" align="center">Home</div>
<div align="center">
<button onclick="myFunction()">Button</button>
</div>
<div id="parentElement" align="center">
<div id="newElement" style="display: hidden"></div>
</div>
<script>
function myFunction() {
var embed = prompt("Please enter your YouTube Embed Link");
if (embed != null) {
document.getElementById("newElement").innerHTML = embed;
$('#newElement').css('display','inline');
}
}
</script>
</body>
</html>
just taking out the parent - child element relationship in javascript code and put the new element div in html with display:none style attribute. Then in click function, just make it visible.
Cheers!
It took sometime to understand your requirement infact still now it is not clear .But from your code I understand that you are trying to get a text from prompt message and initally you want to display it in your page.But that is not working since you are not able to execute it.
document.getElementById("newElement").innerHTML
Rather that using innerHTML you can check textContent.
Here is a minor change in your function
if (embed != null) {
newElement.textContent = embed;
}
WORKING COPY
I know this has been asked before but mine might be a little different.
I have an HTML page that I have little control of and has a restriction on what JavaScript can be used. In this HTML I decalare a variable, in this case an array of image URLs.
In an external file I am trying to use this variable. The variable works anywhere within this file, but as soon as I try and show it within document.ready it becomes undefined.
Making it awkward is that I can't call the external script without writing it in a document.write script (it's within eBay and you can't call external scripts easily)
Can anyone help with why it doesn't work, or a better way of doing it?
I have full control of the JavaScript file, but the HTML I have access to, but limited to what I can write in there without eBay blocking it. It's for this reason the document.write has to be used.
My code is like this (a stripped out version):
console.log("Images: " + prodImgs);
$(document).ready(function() {
console.log("Images inside doc ready: " + prodImgs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<head>
<meta http-equiv="content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var prodImgs = new Array();
prodImgs[0] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[1] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[2] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs[3] = "http://example.com/Media/images/testImages/1.jpg";
prodImgs = prodImgs.filter(function(v) {
return v !== ''
});
document.write("<" + "script src='http://example.com/Scripts/jquery-1.8.1.min.js' type='text/javascript' " + "></" + "script><" + "script src='http://example.com/Scripts/myscripts.js' type='text/javascript' " + "></" + "script>");
</script>
</head>
<body>
If you view the source on eBay, they already reference jquery version 1.7, on the home page anyway.
http://ir.ebaystatic.com/rs/v/jmalt0eyvq1k1k2ezqntv51k5mo.js
Suggest there is possibly a conflict. I would strongly suggest not using jquery unless you must because you will be at the whim of whatever eBay decide to do with their general code base.
Using an iframe to embed the content or features would allow you to have independent code that won't clash with ebay's core, although you will potentially have cross-site scripting errors depending on what you are trying to achieve.
Perhaps a combination of both. I assume you are trying to embed a slide show. Have a iframe hosted elsewhere for that, and then keep to general content and pure javascript if you need.
Remember to use closures and limit globals as again you may conflict with ebays base code.
did you mean you want to declare a variable in your html page.
and want to access that variable in .js file?? if so then in html file when you declare a variable dont use the var keyword.
dont use this
var prodImgs=new Array();
use the below one
prodImgs=new Array(); -- use this.
now you can access the prodImgs variable in .js file
The e-commerce platform I use, bigcommerce, uses global variables to insert data dynamically. I don't have access to the php needed to manipulate the variables server side.
Unless at checkout, the variables all render http: links, I'd like a script to make them relative so if someone wants to browse via https: all of the menu and category links will comply.
I'm currently use this to correct my main nav but it is obviously not a best case solution, and the remainder of the generated links remain http
<script type="text/javascript">
relativeLinking();
function relativeLinking(){
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
};
</script>
you can tranform all links using this code:
$(function() {
$('a').each(function() {
var self = $(this);
self.attr('href', self.attr('href').replace(/.*\/\//,'//'));
});
});
Dustin,
This Javascript code
var GLOBAL_PagePath = "%%GLOBAL_PageLink%%".substring(5);
document.getElementById("%%GLOBAL_PageName%%").setAttribute("href", GLOBAL_PagePath);
sets the attributes. Why require this and not just deliver the correct HTML in the first place.
One assumes that needing this that the web master does not know (or care?) the HTML/PHP/JS etc on the two sites (http:// and https:// protocol).
Certain files should be on one site and nor the other. Vice - Versa.