amphtml icon indicating copy to clipboard operation
amphtml copied to clipboard

[amp-script] event.preventDefault() to be supported by DOM worker

Open Kevin-Ellen opened this issue 7 years ago • 7 comments

SUMMARY

event.preventDefault() to be respected within amp-script, allowing default behaviour by browser to be stopped (such as navigating to links).

WORK-AROUND

As a work-around this I have used <a data-href="/destination">anchor</a> as links, as the browser doesn't treat them as 'links'. They are followed by <noscript><a href="/destination">anchor</a></noscript> elements to ensure that non-JS entities (such as search engines) can crawl the links.

EXAMPLES

AS IS: HTML

<noscript><a href="/destination">anchor</a></noscript>
<a data-href="/destination">anchor</a>

TO BE: HTML

<a href="/destination">anchor</a>

AS IS: JAVASCRIPT

document.querySelectorAll('.link-class').forEach(link =>{
	link.addEventListener('click', function(event){
		var destination = event.target.getAttribute('data-href');
		doStuff(destination);
	});
});

TO BE: JAVASCRIPT

document.querySelectorAll('.link-class').forEach(link =>{
	link.addEventListener('click', function(event){
		event.preventDefault();
		var destination = event.target.href;
		doStuff(destination);
	});

ADDITIONAL

This would be a welcome step towards making Single Page Applications (SPAs) more easily with less technical debt.

Kevin-Ellen avatar Oct 15 '19 00:10 Kevin-Ellen

cc @kristoferbaxter @choumx

nainar avatar Oct 15 '19 00:10 nainar

Thanks for filing this issue. De-duping with #22253.

dreamofabear avatar Oct 15 '19 19:10 dreamofabear

Note that it's not possible to preventDefault in the worker because it runs on a separate thread and by then it'll be too late.

dreamofabear avatar Oct 15 '19 19:10 dreamofabear

@choumx - considering adding an flag to the third argument of addEventListener to support unconditional preventDefault, with a _experimental prefix to avoid causing interop problems with a potential future DOM specification.

kristoferbaxter avatar Oct 16 '19 00:10 kristoferbaxter

Adding onclick="javascript:return false;" works too; and can still listen to the link.

So my HTML link link as follows:

<a class="internal-link" data-href="https://domain.tld/page" href="https://domain.tld/page" onclick="javascript:return false;">Anchor</a>

JavaScript:

link.addEventListener('click', function(event){
	console.log(event.target.getAttribute('href'));
});

Opinions?

Kevin-Ellen avatar Oct 16 '19 05:10 Kevin-Ellen

Please note that onclick="doStuff()" gets sanitised unfortunately.

Kevin-Ellen avatar Oct 16 '19 12:10 Kevin-Ellen

@choumx Could this attitude be adopted?

doradsoft avatar Mar 18 '20 16:03 doradsoft