I have an application which opens another angular application in a new tab on clicking a button. I need to override the title of the new tab from the parent tab and set a value. Some mock code below
<!DOCTYPE html>
<html>
<head>
<title>New tab</title>
</head>
<body>
<div>
<input id="toolId" placeholder="ToolId" style="padding: 4px 0; width: 70px;" />
<button id="button">Launch</button>
</div>
<script>
window.onload = function () {
document.getElementById('button').addEventListener('click', () => {
var newWin = window.open('http://localhost:4200', "_blank");
// add a load listener to the window so that the title gets changed on page load
newWin.onload = function() {
newWin.document.title = 'New Title';
console.log('Loaded');
};
// newWin.document.title = 'New Title';
})
}
</script>
</body>
</html>
But when i try to do this , i always see the default value set by the angular application rather than what is set by the above code. What am i missing here ? Is it blocked by chrome by chance, could not find any relavent doc if it is .
You can find an explanation for this in the documentation:
The problem with <title>:
The obvious approach is to bind a property of the component to the HTML like this:
<title>{{This_Does_Not_Work}}</title>
Sorry but that won't work. The root component of the application is an element contained within the tag. The HTML <title> is in the document , outside the body, making it inaccessible to Angular data binding.
You could grab the browser document object and set the title manually. That's dirty and undermines your chances of running the app outside of a browser someday.
Related
I'm trying to make a loadable widget that would call an api when a button is clicked.
Widget page itself
widget.html
<html>
<head>
<title>Widget</title>
</head>
<body>
<button id="test"></button>
<script>
window.onload = init;
function clicked() {
// some logic
}
function init() {
document.getElementById('test').addEventListener('click', clicked, false);
}
export {clicked}
</script>
</body>
</html>
The page it embeds on
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Getting started</title>
</head>
<body>
<div>
<div id="widget_box"></div>
<script src="http://localhost:8080/js/widget.js" type="text/javascript"></script>
<script type="text/javascript">wdgt.init('widget_box');</script>
</div>
</body>
</html>
js code that loads the widget
widget.js
var wdgt= {
idBox: 'wdgt',
url_widget: 'http://localhost:8080/pages/widgets/widget.html',
url_style: 'http://localhost:8080/css/widget.css',
init: function (id) {
console.log("Begin Widget initialization");
if (!id) {
id = this.idBox;
}
if (document.getElementById(id)) {
this.addStyle();
try {
var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest : XDomainRequest;
var xhr = new XHR();
xhr.open('GET', this.url_widget, true);
xhr.onload = function () {
if (this.response) {
document.getElementById(id).innerHTML = this.response;
}
}
xhr.onerror = function () {
console.log('onerror ' + this.status);
}
xhr.send();
} catch (ignore) {
}
} else {
console.log('The specified block id="' + id + '" is missing');
}
},
addStyle: function () {
style = document.createElement('link');
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = this.url_style;
document.head.appendChild(style);
}
}
If I open the widget in a separate window, the code attached to the button works. But when I try to embed it, nothing happens.
Moreover, in this script, document.getElementById() returns null when trying to find the button.
The back is a simple Spring application that returns index.html
TL;DR: It's not supposed to work. You should use iframe element to fetch and render external pages.
Your script widget.js is trying to render the contents of fetched widget.html into a <div> element.
The browser will to do the best, though it won't be able to create another DOM tree inside of <div>. Because when you feed a whole HTML page to innerHTML, you basically ask the browser to render a document inside a document. This is not allowed.
Still it will render the contents of you document's body. So you'll be able to see the button. But it won't execute any <script> tags. It's a safety measure to prevent XSS attacks. A couple of dirty ways to execute your code do exist, but I won't recommend them.
So what should you do to add an external widget into a page? The answer is neat: meet the <iframe>! This dude is created just for those things. For you case, you should rewrite index.html this way:
<!DOCTYPE HTML>
<html>
<head>
<title>Getting started</title>
</head>
<body>
<iframe src="http://localhost:8080/pages/widgets/widget.html" width="800" height="600"></iframe>
</body>
</html>
With iframes, you don't need to manually fetch your widget HTML. The browser will download and render it inside your iframe. Like a document inside a document with all the styles, embedded resources and scripts.
Please note, that when you embed something using iframe, security limitations apply. You won't be able to directly interact with your main page from inside the iframe and vice versa. It will be like a separate window inside you document. And it will have additional constraints. Please address to the docs.
How do I make a html button run code?
What I'm trying to do is put a button <button> open a new page in about:blank and have the code that was in a <textbox> there.
I don't know how to make the about:blank page have the code though. I have tried:
<button src="about:blank" target"_blank" data-uri="(I don't know what to put here or if this is even correct)">Click to run code</button>
I'm trying to implement it with HTML and JS. If anyone could help, that would be awesome!
This should work in almost all of the browsers (tested in both FF and Chrome):
<!-- Your link !-->
<a id="externalLink" href="#/">Click to run the code</a>
<script>
const el = document.getElementById('externalLink');
// Create a content for a new page with a script in it
const newPageContent = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>alert('Hello World!')<\/script>
Hello world!
</body>
</html>
`;
// Listen on "click" event
el.addEventListener('click', (e) => {
e.preventDefault();
// Create a new window on click
const w = window.open('', '_blank');
// Write your content to it
w.document.write(newPageContent);
});
</script>
While I wasn't able to make the href="data:text/html" work properly. I assume that it should be forbidden by some security rules of the browser.
My goal is to load javascript in the <head> only if a certain element exists in the <body>.
However, I have a problem: I am loading a Web Component, which is just a <script> hosted elsewhere and is pulled in as:
<script src="https://someurl.com/some-web-component.min.js"></script>
This web component file is huge, so I don't want to pull it in unless it is inserted into body by our Content Management System (CMS).
The constraints I am working under are:
• The <head> is shared between pages, so I need conditional logic
• I have no control over the <body> inserted by the CMS, which will potentially contain the <my-web-component> tag
• I NEED the script to load the web component, so I can't use jQuery's $(document).ready, at least I think I can't - an error will be thrown because the browser won't know the element exists
This plunker partially shows my problem, minus all the web component complexity:
https://plnkr.co/edit/GGif2RNHX1iLAvSk1nUw?utm_source=next&utm_medium=banner&utm_campaign=next&p=preview
Any way around this?
You can use DOMContentLoaded event.
The DOMContentLoaded event is fired when the initial HTML document has
been completely loaded and parsed, without waiting for stylesheets,
images, and subframes to finish loading.
In this case you can look for the Component and add the script with something like the following
document.addEventListener("DOMContentLoaded", function(event) {
if(document.querySelector('Component')){
var script = document.createElement('script');
script.src = 'https://someurl.com/some-web-component.min.js';
document.head.appendChild(script)
}
});
Probably a better approach though would be to add the script in the head with async attribute and later remove it if the component is not found.
Something like this
<script async src = "https://someurl.com/some-web-component.min.js"> </script>
<script >
document.addEventListener("DOMContentLoaded", function(event) {
if (document.querySelector('Component') == null) {
var script = document.querySelector('script[src="https://someurl.com/some-web-component.min.js"]')
document.head.removeChild(script)
}
});
</script>
More about DOM lifecycle events
More about async script loading
I am using $(document).ready and inside this method checking if element exists or not. It is working completely fine for me. Below is code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Test Element Exists or Not</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var elem = document.querySelector('h1');
var isElemPresent = !!elem;
console.log('Is the element present: ', isElemPresent);
});
</script>
</head>
<body>
<h1>Hello Plunker!</h1>
<script>
var elem = document.querySelector('h1');
var isElemPresent = !!elem;
console.log('Oh NOW it works...: ', isElemPresent);
</script>
</body>
</html>
I am not sure where you are facing issue while using jQuery. There might be some other issue. Above approach is good enough to load script after checking if element is present.
Plunker link:
https://run.plnkr.co/preview/cjgczwlzt000knneldv5d52ea/
I'm trying to write a web application using the new offline capabilities of HTML5. In this application, I'd like to be able to edit some HTML—a full document, not a fragment—in a <textarea>, press a button and then populate a new browser window (or <iframe>, haven't decided yet) with the HTML found in the <textarea>. The new content is not persisted anywhere except the local client, so setting the source on the window.open call or the src attribute on an <iframe> is not going to work.
I found the following question on StackOverflow: "Putting HTML from the current page into a new window", which got me part of the way there. It seems this technique works well with fragments, but I was unsuccessful in getting an entirely new HTML document loaded. The strange thing is when I view the DOM in Firebug, I see the new HTML—it just doesn't render.
Is it possible to render a generated HTML document in a new window or <iframe>?
EDIT: Here's a "working" example of how I'm attempting to accomplish this:
<!doctype html>
<html>
<head>
<title>Test new DOM</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function runonload() {
return $("#newcode")[0].value;
}
$(function() {
$("#runit").click(function() {
w=window.open("");
$(w.document).ready(function() {
$(w.document).html(w.opener.runonload());
});
});
});
</script>
</head>
<body>
<textarea id="newcode">
<!doctype html>
<html>
<head>
<title>New Page Test</title>
</head>
<body>
<h1>Testing 1 2 3</h1>
</body>
</html>
</textarea>
<br/>
<button id="runit">Run it!</button>
</body>
</html>
I think you are overcomplicating this...
try this:
<SCRIPT LANGUAGE="JavaScript">
function displayHTML(form) {
var inf = form.htmlArea.value;
win = window.open(", ", 'popup', 'toolbar = no, status = no'); win.document.write("" + inf + ""); } // </script>
<form>
<textarea name="htmlArea" cols=60 rows=12> </textarea> <br> <input type="button" value=" Preview HTML (New Window)" onclick="displayHTML(this.form)"> </form>
$(w.document).html(w.opener.runonload());
You can't set innerHTML—or, consequently, jQuery's html()—on a Document object itself.
Even if you could, you wouldn't be able to do it using html(), because that parses the given markup in the context of an element (usually <div>) from the current document. The doctype declaration won't fit/work, putting <html>/<body>/etc inside a <div> is invalid, and trying to insert the elements it creates from the current ownerDocument into a different document should give a WRONG_DOCUMENT_ERR DOMException. (Some browsers let you get away with that bit though.)
This is a case where the old-school way is still the best:
w= window.open('', '_blank');
w.document.write($('#newcode').val());
w.document.close();
Whilst you can inject innerHTML into a pop-up's document.documentElement, if you do it that way you don't get the chance to set a <!DOCTYPE>, which means the page is stuck in nasty old Quirks Mode.
I have an iframe on a page that allows us to upload an image, once it's uploaded it displays the url of the file in a text input field.
On the main part of the page, we have our textarea where we write up our news posts. I'd like a way so that I can add a link on the iframe, next to the url field, that when clicked will automatically insert the text in there into the textarea on the main part of the page.
I'm relatively new to javascript, so I wasn't sure how to do this when using an iframe.
Thanks!
Main.htm
<html>
<head>
<script>
getText = function(s)
{
alert(s);
}
</script>
</head>
<body>
<iframe src="otherFrame.htm"></iframe>
</body>
</html>
otherFrame.htm
<html>
<head>
<script>
botherParent = function()
{
parent.getText(document.getElementById("textInput").value);
};
window.onload = function()
{
}
</script>
</head>
<body>
<input type="text" id="textInput" />
<span onclick="botherParent()">Stuff goes here</span>
</body>
</html>
Basically, in the child inline frame, use parent to access the parent's window object.
Global variables are stored in window, as are global functions. Because of this, if you define a global variable "foo" in parent, you can access it with parent.foo with your child frame.
Hope that helps!
Assuming I understand this correctly you want to be able to use javascript to access information in an iFrame from the container page. This is generally regarded as Cross Site Scripting and is not allowed.