[amp-script] event.preventDefault() to be supported by DOM worker
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.
cc @kristoferbaxter @choumx
Thanks for filing this issue. De-duping with #22253.
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.
@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.
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?
Please note that onclick="doStuff()" gets sanitised unfortunately.
@choumx Could this attitude be adopted?