'javascript:close()' doesn't seem to be working - javascript

I'm really new to JavaScript, but I think this should be pretty simple. I'm just trying to create a link to close my window using: document.write("Close this window");
However, when I click the link created by the above code nothing happens. What am I doing wrong? my entire code is below:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Loops demo</title>
</head>
<body>
<script type="text/javascript">
function openActor() {
actorWin = window.open("","actorWin","height=200,width=600,resizable");
actorWin.document.write("<!doctype html>");
actorWin.document.write("<html lang=\"en\">");
actorWin.document.write("<head>");
actorWin.document.write("<meta charset=\"utf-8\">");
actorWin.document.write("<title>Keira Knightley</title>");;
actorWin.document.write("</head>");
actorWin.document.write("<body>");
actorWin.document.write("Info on, one of the great actors of our time.");
actorWin.document.write("</body>");
actorWin.document.write("</html>");
}
function Movie(title, actor, web1, web2) {
this.title = title;
this.actor = actor;
this.link = web1;
this.link2 = web2;
}
var movie1 = new Movie('Pride and Prejudice', 'Keira Knightley', 'http://movies.yahoo.com/movie/pride-and- prejudice-2005/','http://keiraknightleyfan.com/');
document.write(movie1.title + '<blockquote>“A lady\'s imagination is very rapid; it jumps from admiration to love, from love to matrimony in a moment.” ― Jane Austen, Pride and Prejudice</blockquote>');
document.write('Read more about Pride Prejudice<br>');
document.write("<a href='javascript:openActor()'>Click here for info on the lead actor</a><br>");
document.write("<a href='javascript:close()'>Close this window</a>");
</script>
</body>
</html>

You cannot close windows by using close() when they haven't been opened via javascript

There is no function named close.
javascript:close(); simply calls the function close.
If you want to close the popup window, you will need to call close on that.
Like: javascript:actorWin.close();
In that case, make sure you declare the actorWin in the global scope (put var actorWin; just above function openActor...).

Try window.close()
document.write("<a href='javascript:window.close()'>Close this window</a>");

Related

Drawing .svg with javascript module "RDKIT-JS"

first of all I'm relatively new to javascript. So I'm sorry if my question is dumb. I would like to draw a molecule on my webiste by using this tool https://github.com/rdkit/rdkit-js. I also found an example here https://iwatobipen.wordpress.com/2021/12/29/create-desktop-chemoinformatics-application-with-js-chemoinformatics-rdkit-js/comment-page-1/. This example works in my case but when i try to invoke a function to draw a molecule as a .svg without using the example code, I fail. I get this error-message in my browser:
Uncaught ReferenceError: RDKit is not defined
at drawmol (results:21:15)
at results:33:5
In the following code example you can see the first case where it works and the second case were it doesn't. In both cases i use the same function.:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/#rdkit/rdkit/dist/RDKit_minimal.js"></script>
<title>Document</title>
<script>
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
})
.catch(() => {
});
</script>
<script> var drawmol = function() {
var mol = RDKit.get_mol("C1=CC=C(C=C1)O"); // the string here is a string representation of chemical molecules, it could also be something like "CO" or "CCCCC", shouldnt be important
var svg = mol.get_svg();
document.getElementById("drawer").innerHTML = svg;
};
</script>
</head>
<body>
<button type='button' onclick='drawmol()'> <!-- this works -->
draw
</button><br>
<script>
// drawmol() //this doesnt work
</script>
<div id='drawer'></div>
</body>
</body>
</html>
Later i would like to use the module to dynamically make those images. I use django as the framework. In this case i tried to present a minimal example without the django stuff.
Thanks in advance for your effort!
You are calling drawmol() before RDKit is ready.
To fix this, place it after RDKit is loaded:
window
.initRDKitModule()
.then(function (RDKit) {
console.log("RDKit version: " + RDKit.version());
window.RDKit = RDKit;
//Now RDKit is loaded you can safely call drawmol()
drawmol();
})
.catch(() => {
});

focus child window from another child window

I have the following scenario like this :
I have a main window[main.html]. There are three links called Popup1, Popup2, Popup3. On clicking the link open Popup1 window, Popup2 window respectively.
<html>
<head>
<title>Popup Focus Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
var openWin = [];
$(function(){
$('#elem').on('click', 'a', function(){
var index = $(this).index();
var page = 'pop'+(index+1)+'.html';
var w = window.open(page, $(this).attr('title'), '_blank');
openWin[index] = w;
});
});
</script>
</head>
<body>
<div id="elem">
Pop 1
Pop 2
Pop 3
</div>
</body>
</html>
Now the windows open are window 1 & window 2. I want to transfer the focus of the window 1 from window 2. is there anyway this can be done?
pop1.html
<html>
<head>
<title>Popup 1 Example</title>
<script type="text/javascript">
function go() {
if(window.opener.openWin) {
var popup2 = window.opener.openWin[1];
popup2.focus();
}
}
</script>
</head>
<body>
<div>
popup 1 example
</div>
<div>Go to Popup2</div>
</body>
</html>
pop2.html
<html>
<head>
<title>Popup 2 Example</title>
</head>
<body>
<div>
popup 2 example
</div>
</body>
</html>
Check main.html code in fiddle http://jsfiddle.net/tmf8cry8/2/
You have written the code properly, please implement the two changes as listed below...
1) You need to push the window object in openWin Array
var openWin = [];
$(function(){
$('#elem').on('click', 'a', function(){
var index = $(this).index();
var page = 'pop'+(index+1)+'.html';
var w = window.open(page, $(this).attr('title'), '_blank');
//openWin[index] = w;
openWin.push(w); //Push the window object
});
});
2) Access the window object using the array index to focus the window
function go() {
//console.log(openWin);
//if(window.opener.openWin) {
// var popup2 = window.opener.openWin[1];
//popup2.focus();
//}
//Supposing that pop1, pop2 and pop3 are opened, you want to access pop2
openWin[1].focus();
}
Hope it helps!
You can use the method window.open
window.open("",window_name).focus();
Assuming your window is opened, you can transfer focus to the window using the above code.
Please use the following code in pop2.html and try [after opening all windows in a sequential order].
<html>
<head>
<title>Popup 2 Example</title>
<script language="javascript">
function openNew()
{
window.open("","Pop 3").focus();
}
</script>
</head>
<body>
<div>
popup 2 example
</div>
<a href="javascript:void(0);" onclick="javascript:openNew();">
Go to pop3</a>
</body>
</html>
As per you code, you are using title attribute to naming windows, hence Pop 3 is used to transfer focus to Pop 3 window.
Alternatively, you may check if the window instance is opened or not and then load the URL entirely or transfer focus
Hope it helps!!!
Make go() function just call a function in the opener window, e.g.:
window.blur(); //focus out of here
window.opener.myParentWindowFunction( 2 );
That function (in the "parent" window) should call then a function in the target window that just "window.focus()".
funtion myParentWindowFunction( target ){
window.blur();//focus out of here also
openWin[target].callFocus();
}
And on every popup:
function callFocus(){ window.focus(); }
You can't make a window "send" the focus to another (security issues I guess), but you can make a window to "ask for it"... and depends on the browsers if it's going to get it (in chrome doesn't work, but if you add an alert() after the focus it will change the window. Funny, because if you just put the alert but not the focus it doesn't swap the windows...)
Code is just a mockup, but that's the concept. You have to use the opener window as relay comunicate to the desired window that it have to call the focus. Hope you don't need it really crossbrowser.

Open multiple links in Chrome at once as new tabs

I'm trying to open multiple links at once in Google Chrome in new tabs but it fails.
Problems:
Blocked by popup
Open in new windows instead of tab after the user allowed the popup
With this, I can open multiple links at once in Firefox:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" >');</script>
<link rel="stylesheet" href="style.css">
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="openLinks()">Open</button>
</body>
</html>
Also, I came across someone who found a workaround.
I tried using setInterval to try to open the links individually but it didn't work.
You can do this in vanilla JavaScript:
<html>
<head>
<script type="text/javascript">
function open_win() {
window.open("http://www.java2s.com/")
window.open("http://www.java2s.com/")
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
</html>
Here is a more Chrome-specific implementation (if popup blockers are giving you difficulty):
var linkArray = []; // your links
for (var i = 0; i < linkArray.length; i++) {
// will open each link in the current window
chrome.tabs.create({
url: linkArray[i]
});
}
Here is some documentation: https://developer.chrome.com/extensions/tabs
The reason that the browser extension can do it is because Chrome extensions have access to a special Chrome API, which lets you use:
chrome.windows.create({tabid: n})
where createData has a tabid value greater than any current tab (and you can find the greatest current tabid using chrome.windows.getAll()).
However, in terms of doing it on your page (or anywhere that's not a Chrome extension), that's not possible, since whether or not a new window opens in a new tab is determined entirely by the user's settings.
The best way to open multiple tabs or windows is by using setTimeout() of 500ms.
window.open("https://facebook.com", "one", windowFeatures);
setTimeout(function(){
window.open("https://facebook.com", "two", windowFeatures);
}, 500);
User will have to allow popups but I ended up doing this:
function openMultipleTabs(urlsArray){
urlsArray.forEach(function(url){
let link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.click();
});
}
Worth mentioning that you need to actually have popups allowed in your browser settings. Don't rely on browser alert asking you if you want to allow the popup to open.
The following code will open multiple popUp on the button click.
<html>
<head>
<title></title>
<script type="text/javascript">
function open_win() {
window.open("url","windowName","windowFeatures")
window.open("url","DifferentWindowName","windowFeatures")// different name for each popup
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
you need to make sure that each window name is different, otherwise the last popup will overwrite it's previous popup. As a result you will end up with a single popup.
I have a simple solution playing with setTimeout, check below
function openMultipleTabs(urlsArray: string[]) {
urlsArray.forEach((url: string, key: number) => {
if (key === 0) {
window.open(url, `_blank_first_${key.toString()}`);
} else {
setTimeout(function () {
console.log("resolved", key);
window.open(url, `_blank_${key.toString()}`);
}, 1500 * key);
}
});
}
Looks like extension uses below code to open those tabs.
function openTab(urls, delay, window_id, tab_position, close_time) {
var obj = {
windowId: window_id,
url: urls.shift().url,
selected: false
}
if(tab_position != null) {
obj.index = tab_position
tab_position++;
}
chrome.tabs.create(obj, function(tab) {
if(close_time > 0) {
window.setTimeout(function() {
chrome.tabs.remove(tab.id);
}, close_time*1000);
}
});
if(urls.length > 0) {
window.setTimeout(function() {openTab(urls, delay, window_id, tab_position, close_time)}, delay*1000);
}
}
If you want to take a look at the code of the extension for reference you will find the extensions in (for Windows) C:\Documents and Settings\*UserName*\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions
Since modern browsers (and even old ones with blockers), will absolutely not allow this (one user action, one new tab). My solution was:
openInfoLinks = () => {
const urlsArray = [
`https://...`,
`https://...`,
`https://...`,
]
window.open(
urlsArray[this.linkCounter],
`_blank_${someIdentifier}_${this.linkCounter}`
);
this.linkCounter++;
setTimeout(() => {
this.linkCounter = 0;
}, 500);
}
The user can open the links in quick succession with ctrl+click-ing the button N times.

How do I use JQuery inside an object constructor in my own javascript namespace?

I can't even find a hint of an answer to this question anywhere, so maybe I'm totally barking up the wrong tree...
I'm making a javascript namespace, inside of which I am putting a constructor function:
var SEP=SEP||{};
SEP.person=function(name)
{
this.name=name
this.sayName=sayName
function sayName()
{
return this.name;
$(document).ready
(
function()
{
$('body').css('background', 'red');
}
);
}
}
Then I am calling the function from the HTML...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>test</title>
<meta name="generator" content="BBEdit 10.5" />
</head>
<body>
<script src="libraries/jquery/javascript/jquery-1.11.0-min.js"></script>
<script src="libraries/sep/javascript/sep.js"></script>
<p>Hello</p>
<script>
var bob=new SEP.person("bob");
word=bob.sayName();
document.write(word);
</script>
</body>
</html>
Question one is, why doesn't this work?
Question two is how can I make it work?
Question three is, if I want to make a more involved constructor, with JQuery peppered thoughout, do I need to do the document ready thing over and over, or is there a better way?
Many thanks in advance.
Actually your constructor is working fine. But you should not use document.write in your code. Instead you can append the value to a html tag, using either .append() .html() or .text() methods. Also there should be a small change in your sayName() method, Css should apply before return. Otherwise it will not hit on those lines of code.
var SEP = SEP || {};
SEP.person = function (name) {
this.name = name
this.sayName = sayName
function sayName() {
$('body').css('background', 'red');
return this.name;
}
}
var bob = new SEP.person("bob");
word = bob.sayName();
$("span").text(word);
Demo

Access function from background page in Chrome extension

In my background (background.html) page I have the following js:
function capturePage(){
chrome.tabs.captureVisibleTab(null, function(img){
var screenshotUrl = img;
chrome.tabs.create({"url":"history.html"}, function(tab){
var t = tab;
var addImage = function(){
var view = chrome.extension.getViews()[0];
view.setImageUrl(screenshotUrl);
}
chrome.tabs.onUpdated.addListener(addImage);
});
});
}
chrome.browserAction.onClicked.addListener(capturePage);
and in history.html I have:
<html>
<head>
<title></title>
<script>
function setImageUrl(url){
document.getElementById("target").src = url;
}
</script>
</head>
<body>
<img id="target" src="" >
</body>
</html>
However, "view.setImageUrl(screenshotUrl)", in background.html, fails as it says the view has no such function. Just to be clear, I'm trying to access a function within history.html AND pass a parameter to it (screenshotUrl).
EDIT: re Serg's suggestion I replaced the var addImage function in background with the following:
var port = chrome.tabs.connect(tab.id,{name: "history_connect"});
port.postMessage({mType:"url",url:screenshotUrl});
Then added a listener on the history page... worked!
I haven't used getViews() before so I can't comment on that (what does console say when you dump chrome.extension.getViews() into it?), but here is couple workarounds:
Pass your url as get parameter during tab creation (history.html?url=<urlencoded_url>)
Use requests. chrome.extension.sendRequest({url:url}); in bkgd page and chrome.extension.onRequest.addListener() in history.html
Use "pull" instead of "push". In history.html you can use chrome.extension.getBackgroundPage().getMyUrl()
I would use the first solution as it is the easiest and fastest.

Categories

Resources