I've been trying to create a custom homepage/new tab extension that uses html to show a bunch of tiles which link to sites that I frequently use.
I think I'm using a somewhat janky way of creating these 'tiles', but long story short I want to get one to execute some javascript in order to open a new incognito window (re here) I've tried using the onclick / onsubmit for the form/button elements to no success & tried giving the form an id then creating an eventlistener for click - also which I couldnt get to work.
Bit of a beginner in this area, any advice on where to start would be appreciated
Code for each of the 'tiles':
<form>
<button formaction="https://UrlHere">
<img src=".\AssetHere" />
<label><span>Description here</span></label>
</button>
</form>
<script src="newInPrivate.js"></script>
CodePudding user response:
I'm pretty sure you don't need any form, just a bunch of buttons.
Whatever you pass to the onclick
attribute is executed once the user clicks the button.
I suggest creating a function that receives a URL and using the chrome API to open the tab in incognito. Here is an example of the function implementation, as described here.
function openUrlInNewIncognitoTab(url) {
chrome.windows.create({
url, // that's the same as url: url
incognito: true
});
}
Then, for each button you display, set the onclick
attribute to openUrlInNewIncognitoTab('https://UrlHere')
.
You'll get a button like this:
<button onclick="openUrlInNewIncognitoTab('https://UrlHere')">
<img src=".\AssetHere" />
<label><span>Description here</span></label>
</button>
CodePudding user response:
You can only do this in an extension
Either use click (simpler)
document.getElementById("buttonDiv").addEventListener("click", e => {
e.preventDefault()
windows.create({"url": e.target.getAttribute("formaction"), "incognito": true});
})
<div id="buttonDiv">
<button formaction="https://google.com">
<img src=".\AssetHere" />
<label><span>Description here</span></label>
</button>
</div>
or submit event handler:
document.getElementById("buttonDiv").addEventListener("submit", e => {
e.preventDefault()
windows.create({"url": document.activeElement.getAttribute("formaction"), "incognito": true});
})
<div id="buttonDiv">
<form>
<button formaction="https://google.com">
<img src=".\AssetHere" />
<label><span>Description here</span></label>
</button>
</form>
</div>
CodePudding user response:
You need to pass the target URL as a parameter to that function e.g. if there is a function newInPrivate(url)
then :
<form>
<button onclick="newInPrivate('https://UrlHere')">
<img src=".\AssetHere" />
<label><span>Description here</span></label>
</button>
</form>
If you are looking for a general click listener instead of editing the formaction attributes then:
$(document).ready(function(){
$('button[formaction]').click(function(e){
e.preventDefault();
var targetUrl=$(this).attr("formaction");
newInPrivate(targetUrl);
return false;
})
})