Open a new tab with custom HTML instead of a URL - javascript

I'm making a Greasemonkey script and would like to open a new tab which will not display a URL but some HTML that is part of the script. So basically I want to do something like this (which is obviously not working):
window.open('<html><head></head><body></body></html>');
or
GM_openInTab('<html><head></head><body></body></html>');
Any hints are welcome!

You can do this:
var newWindow = window.open();
and then do
newWindow.document.write("ohai");

April 2021 Edit: This answer is obsolete now. Chrome banned loading data URIs into the top window, and the iframe solution doesn't work for me in Firefox.
Original answer: If the other answer gives you Error: Permission denied to access property "document", see this question about how to handle same-origin policy problems, or this one.
Or, quick and dirty, use a data URI:
var html = '<html><head></head><body>ohai</body></html>';
var uri = "data:text/html," + encodeURIComponent(html);
var newWindow = window.open(uri);

I am putting this here just in case anyone will need this. I have made a way to solve this problem, i created a little website (https://tampermonkeykostyl.dacoconutnut.repl.co) that you can give html to in the hash! Example: (you might need to middle click the url for it to actually open in new tab)
// get url
var el = document.getElementById("url");
// make html
var HTML = `
<h1>hi</h1>
if you can see this then cool <br>
<i>this should be italic</i> and <b>this should be bold</b>
`;
// insert html after the link to demonstrate
document.body.insertAdjacentHTML("beforeend", HTML); // https://stackoverflow.com/a/51432177/14227520
// set url href
el.href = "https://tampermonkeykostyl.dacoconutnut.repl.co/#" + encodeURI(HTML);
// make it open in new tab
el.target = "_blank";
<a id="url">Click here to display following HTML in a link (see js):</a>

Let's say you have a .html file locally stored. What you can do is this:
var newWindow = window.open();
newWindow.document.location.href = "/path/to/html/file";

Related

Button not showing in Plone, onclick also not working

I am editing a plone page to open an Excel document on a specific sheet. I created two buttons to see if either would appear as actual buttons and use the JS function I reference. With this code the exact part of the page looks like the image below.
Why is only text showing instead of the button and why is the onclick attribute not working?
Note: I have changed to links to the spreadsheet for posting it on here but the link has been tested on other webpages
<script type="text/javascript">
function Open_Excel_File(path,sheet)
{
fso = new ActiveXObject("Scripting.FileSystemObject");
if (!fso.FileExists(path))
alert("Cannot open file.\nFile '" + path + "' doesn't exist.");
else
{
var myApp = new ActiveXObject("Excel.Application");
if (myApp != null)
{
myApp.visible = true;
Book = myApp.workbooks.open(path);
var excel_sheet = Book.Worksheets(sheet).Activate;
myApp.range(f_range).Select;
}
else {
alert ("Cannot open Excel application");
}
}
}
</script>
<div>
<button onclick='Open_Excel_File("file://///fs-01\Departments\Underwriting\Statistical%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%\Cancer%20Statistics%.xlsx", "Vulvar Ca");'>Open File</button>
<input type="button" onclick="Open_Excel_File('file://///fs-01\deps\uw\stat%20Data%20and%20Medical%20Information\Statistics\Cancers\Cancer%20Statistics%202018\Cancer%20Statistics%.xlsx', 'VCA');'>OPEN FILE</input>
</div>
your onclick value is not a function, it is the result of a function call. Try to change that to onclick="Open_Excel_File"; You'll have to provide the file path at some point
Accessing file system from browser is super restricted for security matters, the only way I see fit is to have a file input and using what user provides
Also Plone filter out a bounce of potential "nasty" tags through a specific configurable tool.
It seems to me that you have injected the in the source HTML of a Page (document) type.
If so, you will see in your browser that in, the page source code, the script tag has been totally stripped away.
So,
a correct way to inject some js in your page, is to load it as portal_javascript resource (plone<=4) or in resource_registry (plone>=5).
tha nasty way is to access, in the ZMI, at https://yourseite:8080/Plone/portal_transforms/safe_html/ and configure it to accept script tags inside a document (all document in your site actually).
If this answer does not satisfy you try to ask in the official community:
http://community.plone.org
hth,
alessandro

Featherlight, JavaScript source for dynamic content

I'm evaluating Featherlight lightbox and I'm not able to implement code that satisfies my use case. I need a lightbox that will be used as a report viewer which displays dynamically created content assigned to a JavaScript variable. The value of the string is a valid HMTL5 page.
I've looked at the iframe example, but it depends upon a static iframe being in the DOM. That's not what I need.
I've reviewed this GitHub issue and this jsfiddle and I'm not able to successfully modify the fiddle to display a string.
This is an example of the string I would like to display:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
Is this possible and if so how?
I expect that $.featherlight() will be called manually in response to a button click.
The solution I came up with was to modify the Featherlight source code in 2 places as indicated in this block of code (currently around line 383).
iframe: {
process: function(url) {
var deferred = new $.Deferred();
var $content = $('<iframe/>')
.hide()
.attr('src', url)
.attr('id', this.namespace + '-id') // [KT] 10/31/2016
.css(structure(this, 'iframe'))
.on('load', function() {if ($content.show()) {deferred.resolve($content.show()) } else {deferred.resolve($content)} ; }) // [KT] 10/31/2016
// We can't move an <iframe> and avoid reloading it,
// so let's put it in place ourselves right now:
.appendTo(this.$instance.find('.' + this.namespace + '-content'));
return deferred.promise();
}
},
The id attribute is added to the iframe so content can be added by JavaScript, like this:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
var oIframe = document.getElementById('featherlight-id'); // Featherlight's iframe
var iframeDoc = (oIframe.contentDocument || oIframe.contentWindow.document);
iframeDoc.open();
iframeDoc.write(s);
iframeDoc.close();
This then works:
$.featherlight({iframe: 'about:blank', iframeWidth: '96%' });
The 2nd modification is required so that the url 'about:blank' doesn't raise an error.
I also modified the css so as to get the scroll bars to work as needed.
Edit: the issue with Featherlight not opening an iframe when the url is abount:blank has been fixed as of version 1.5.1.
Edit 2: Using v1.5.1, this works without having to make a modification to Featherlight to add an id to to the iframe:
var s = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Title of the document</title></head><body><p>Content of the document......</p></body></html>';
$.featherlight({iframe: 'about:blank'});
var $iframe = $('.featherlight iframe');
$iframe.ready(function () {
$iframe.contents().find("body").append(s);
});
The accepted SO answer was used for this solution.

Is This Possible in a Browser? [JavaScript / HTML]

I have Javascript code that opens ISBNs of books on Amazon using hyperlinks (feel free to try, for example: 0133098648). I would like the URL to open up on a new window with all links clicked in a new tab on that same window. It appears one can only open in a new tab of the current window, or a new window every time.
Is what I am looking to do even possible? I've been reading that something like this is restricted by browsers for security reasons; Maybe there's a work around? I've been pulling my hair out trying to find a solution for this, if I could it would make my life much more easier.
A picture to describe my question: http://imgur.com/a/5lUP4
Please use JSfiddle example: http://jsfiddle.net/mq1efed2 ( Code does not work on Stackoveflow)
<html>
<div><b>ISBN Hyperlinker</b></div>
<textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea>
<div><b>Hyperlinked text:</b></div>
<div id="output" style="white-space: pre"></div>
<script>
//the input box.
var input = document.getElementById('numbers');
var output = document.getElementById('output')
var base =
'https://www.amazon.ca/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:\d\s*?){10,13})\b/gm);
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item.replace(/\D+/g, ''));
container.appendChild(link);
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
handler(); // run on load
</script>
</html>
No, this isn't possible. Web pages cannot dictate whether or not content opens up in tabs or new windows. It's up to the user/browser to decide.
At best, you can open a new window with window.open(), but that doesn't give you control over tabs in a specific window later.

Reload iframe src / location with new url not working in Safari

I have a page that loads with initially just a form within an iframe, something like this:
<iframe id="oIframe" ...src='somePage>'
<form ... />
</iframe>
When you click a button in the form, some javascript is invoked that builds a url and then I want to do the following:
frame.src = 'somePage?listId=1';
This works in IE to "reload" the frame with the new contents.
However, in Safari this does not work.
I have jQuery available, but I don't want to replace the existing iframe because there are events attached to it. I also can not modify the id of the iframe because it is referenced throughout the application.
I have seen some similar issues but no solutions that seem to work well for my exact issue.
Any assistance anyone can provide would be great!
Some browsers don't use "src" when calling the javascript object directly from the javascript hierarchy and others use "location" or "href" instead of "src" to change the url . You should try these two methods to update your iframe with a new url.
To prevent browser cache add a pseudo-random string like a number and timestamp to the url to prevent caching. For example add "new Date().getTime()" to your url.
Some calling examples:
document.getElementById(iframeId).src = url;
or
window.frames[iframeName].location = url;
I recommend the first option using document.getElementById
Also you can force the iframe to reload a page using
document.getElementById(iframeId).reload(true);
So the answer is very simple:
1. put a <div id="container"> </div> on your page
2. when reload needed use following jQuery:
$("#container").empty();
$("#container").append("<iframe src='" + url + "' />");
and that's it.
Of course there is more elegant way of creating DOM with jQuery but this gives the idea of "refreshing" iframe.
Works in FF18, CH24, IE9, O12 (well it's jQuery so it will work almost always :)
I found a better solution (albeit not paticularly eloquent) for this using jQuery.ajax:
jQuery.ajax({
type: 'GET',
url: "/somePage?someparms",
success: function() {
frameObj.src = "/somePage?someparms";
}
});
This forces the DOM to be read within the frame object, and reloads it once the server is ready to respond.
Try this
form.setAttribute('src', 'somePage?listId=1');
Well, I was able to find what appears to be a feasible solution -- it's a work in progress, but this is basically what I ended up doing:
var myFrame = document.getElementById('frame'); // get frame
myFrame.src = url; // set src attribute of original frame
var originalId = myFrame.id; // retain the original id of the frame
var newFrameId = myFrame.id + new Date().getTime(); // create a new id
var newFrame = "<iframe id=\"" + newFrameId + "\"/>"; // iframe string w/ new id
myFrameParent = myFrame.parentElement; // find parent of original iframe
myFrameParent.innerHTML = newFrame; // update innerHTML of parent
document.getElementById(newFrameId).id = originalId; // change id back
I ran into this issue using React, passing the key as props.src solved it
const KeyedIframe = ({children, ...props}) => <iframe key={props.src} { ...props}>
{children}
</iframe>

YouTube Iframe embedding causes redirect in IE7

This piece of code works for every browser except IE7. In IE7, the user is redirected to http://www.youtube.com. Oh, and it doesn't just redirect the frame, the entire page is redirected! Any thoughts? Ideas? Alternate patterns?
Please help me. IE is killing my will to live.
$('.youtube .cue a').live('click', function(e) {
e.preventDefault();
var $this = $(this);
var $area = $this.parents('.youtube');
var $caption = $area.find('.videoDescription');
var $li = $this.parents('li:first');
var vid = $.trim($(this).attr('href').replace('#', ''));
var title = $li.find('.title').text();
var time = $li.find('.time').text();
var description = $li.find('.description').text();
var $frame = $('<iframe></iframe>').attr({
width:595,
height:350,
frameborder: 0,
src: 'http://www.youtube.com/embed/' + vid
});
if (!hasFlash) {
$area.find('.captioned').html('Please install Flash.');
}
else {
$area.find('.captioned').html('').append($frame);
}
$caption.find('.title').html(title);
$caption.find('.time').html(time);
$caption.find('.description').html(description);
});
It looks to me like this line:
var vid = $.trim($(this).attr('href').replace('#', ''));
is the problem. Retrieving the href from the <a> tag is going to return a fully qualified URL (including http:// and domain on the front). Then, in this line, you're going to add it onto the end of another fully qualified URL:
src: 'http://www.youtube.com/embed/' + vid
That's going to yield an odd result like this:
http://www.youtube.com/embed/http://www.domain.com/xxxxxx
for the iframe src= attribute which is likely not what you want.
What may be tripping you up is that retrieving the href from an <a href="index.html"> tag retrieves a fully qualified URL, even if the page source only has a relative URL. If you only want the path or filename from that link href, you will have to parse that off.
I've verified with a reconstruction of your your HTML and your code that if you give this sort of bad URL to the iFrame, it will redirect the whole page (even in Chrome). Here's the jsfiddle: http://jsfiddle.net/jfriend00/4P3dh/.
If you hit Run and then click the link that says "Click Me", it will redirect the whole page because of the bad URL on the iFrame.

Categories