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.
Related
Essentially, I would like to querySelect a specific text node on the page and replace that node's textContent/data. I have successfully done this via Chrome Console, but when I try to replicate the steps in Tag Manager, I'm seeing nothing happen.
Here is the structure of the relevant portion:
The phone number I need to replace is blacked out. As you can see, I can querySelect this by targeting span.telephone b and then the second childNode.
Here is the node tree for the b element:
The steps I went through in the Console were...
var ogtel = document.body.querySelector("span.telephone b");
var split = ogtel.childNodes[1];
split.textContent;
" (555) 555-5555"
split.replaceData(0,15," new telly baby");
But when I fire a Custom HTML tag in GTM that does the same thing, it shows the tag successfully firing, but that number on the page isn't replace in preview mode.
Here's that Custom HTML tag script. I tried replaceData() and deleteData()...
<script> ( function () {
var ogtel = document.body.querySelector("span.telephone b");
var tel = ogtel.childNodes[1];
var tel2 = tel.deleteData(0,15);
} ) </script>
Any idea what I'm doing wrong? Can GTM even select/edit/delete text data within nodes like this?
ANSWERED!
I wasn't activating the function (like an idiot...)
New GTM code that works..
<script> function changeTel() {
var ogtel = document.body.querySelector("span.telephone b");
var tel = ogtel.childNodes[1];
var tel2 = tel.deleteData(0,15);
}
change = changeTel();
</script>
I am working on a bookmarklet that makes an href link of the current browser tab and copies it to the clipboard. This bookmarklet works in Safari:
javascript:
!function(a){
var%20b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,document.body.appendChild(b),
c.removeAllRanges(),b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b)}
('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');
But in Firefox 65, I get the error "document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler." In looking at Copying to clipboard with document.execCommand('copy') fails with big texts I'm trying to generate the html of the link before the function to solve the issue pointed out in the answer. But, with the code below, I get a new browser tab with the text "true" and no copied link to the clipboard.
javascript:
const text = ('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');
!function(a){
var%20b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,document.body.appendChild(b),
c.removeAllRanges(),
b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b)}('text');
Is this a timing issue with the generation of the href link? Or something else?
Your problem is not the same than in the other Q/A: In your case, you don't have any user-triggered event.
So no, it is not a timing issue, it's just that you need such an event.
To force it, you could show a splash screen, requiring that the bookmarklet's user clicks on the page. From this click event you'd call execCommand('copy').
javascript:(function(a){
var splash = document.createElement('div'),
msg = document.createElement('span');
splash.style='position:fixed;top:0;left:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:#FFF;z-index:999999';
msg.textContent = 'click me';
splash.append(msg);
// wait for the click event
splash.onclick = evt => {
var b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,
document.body.appendChild(b),
c.removeAllRanges(),
b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b),
document.body.removeChild(splash);
};
document.body.append(splash);
})
Here is a live example of what happens (obviously not as a bookmarklet):
(function(a){
var splash = document.createElement('div'),
msg = document.createElement('span');
splash.style='position:fixed;top:0;left:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:#FFF;z-index:999999';
msg.textContent = 'click me';
splash.append(msg);
// wait for the click event
splash.onclick = evt => {
var b=document.createElement("textarea"),
c=document.getSelection();
b.textContent=a,
document.body.appendChild(b),
c.removeAllRanges(),
b.select(),
document.execCommand("copy"),
c.removeAllRanges(),
document.body.removeChild(b),
document.body.removeChild(splash);
};
document.body.append(splash);
})
('<a%20title="'+document.title+'"%20href="'+document.location.href+'">'+document.title+'</a>');
<textarea>You can paste here to check what's been copied</textarea>
File 1 has the following script in it:
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') ;
localStorage.setItem("imgid",selected);
var varmodal = document.getElementById('myinfomodal');
var span = document.getElementsByClassName('infoclose')[0];
varmodal.style.display = "block";
span.onclick = function() {
varmodal.style.display = "none";
}
}
The above script opens the following div/iframe (also in File 1):
<div id="myinfomodal" class="infomodal">
<div class="infomodal-content">
<button class="infoclose">Close</button>
<iframe id="frameid" src="https://outzeal.com/zp2.php" width="100%" height="500px;" style="border:none;"></iframe>
</div>
</div>
The variable selected is supposed to be transferred through localStorage to a second file. The script in the second file is:
window.onload = function () {
var a = localStorage.getItem("imgid");
document.getElementById("demo").innerHTML = a;
if(a == 0){
document.getElementById("demo").innerHTML = "no image selected";
}
}
Please click on this link (not available anymore) for a demo. After clicking on the image the image opens in a modal div. Selecting the check box and clicking on the "Cart icon" opens the div and the iframe file but does not show the value of the variable selected (probably because the function should run after window.onload happens and that has never happened here). If the second file is opened separately (window.onload happens here) the value is shown. I want the value of selected in the modal div. How can that be done? Thanks.
Your code has nothing wrong, it's just a cache problem: I copied your code on my local, of course using zp2.html instead zp2.php (I don't have a PHP server) and it seems to works pretty good: I've got both "no image selected" and "skiing/001", instead on the remote I don't see anything (I think it's because a previous behaviour of zp2.p.
Try to edit your zp2.php and use anonymous navigation, or disable the cache on your browser.
PS: Anyway if you change the value of the checkbox after push the button, the iframe will show the first value because you're using window.onload on zp2.php... If you need a popup you don't need to use iframe and another server page, neither localweb, you can use a global javascript variable.
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";
I am using Internet Explorer.
I added a context menu item (through the registry) such that when right clicking on a link in a webpage a custom menu item pops up. Upon selection, this menu item runs some javascript code.
I want to use the url of the link (on which I right click) in the javascript code - how do I access that url?
*Note that this should work for any webpage, not only ones which I have control over.
Thanks in advance!
<script language="JavaScript">
var parentwin = external.menuArguments;
var doc = parentwin.document;
var url = doc.URL;
// ... the rest of your code here ...
See also.
To get the source object, try:
<script language="JavaScript">
var parentwin = external.menuArguments;
var srcElement = parentwin.event.srcElement;
if (srcElement.tagName == "A") {
var url = srcElement.href;
// ... the rest of your code here ...
}