Búsqueda de sitios web

javascript - el elemento <a> no redirige a otra página y no es clicable


Creé un componente web en el que declaré un método que crea una cadena de copyright:

'<p>Copyright © 2020 Krzysztof Kaczyński<a href="https://www.google.com">. Policy terms</a></p>'

Entonces estoy convirtiendo esta cadena en HTMLParagraphElement y la añado al elemento footer. Cuando abro el navegador web no veo ningún error y puedo ver mi elemento de copyright. Si inspecciono este elemento, también se ve correcto, pero si hago clic en la parte <a> de este elemento no pasa nada (aunque debería redirigir a https://www.google.com).

  • ¿Por qué este <a href="https://www.google.com">. Términos de la política</a> no redirige a https://www.google.com después de hacer clic?
  • ¿Cómo puedo arreglar esto?

Componente AppFooter:

export class AppFooter extends KKWebComponent implements KKAppFooter {
    public static TAG: string = `${CONSTANTS.TAG_PREFIX}-app-footer`;

    public readonly shadowRoot!: ShadowRoot;

    private footer!: HTMLElement;

    constructor() {
        super(template);
        this.getElementsReferences();
    }

    protected getElementsReferences(): void {
        this.footer = <HTMLElement>this.shadowRoot.querySelector('footer');
    }

    public setCopyright({ year, author, termsReferenceUrl }: CopyrightProps): void {
        const copyrightText: string = AppFooter.formattedCopyrights`Copyright © ${year} ${author}. Policy terms${termsReferenceUrl}`;
        this.footer.appendChild(new StringElementConverter().toElement(copyrightText));
    }

    private static formattedCopyrights(strings: TemplateStringsArray, ...values: string[]): string {
        const policyTermsUrlText: string = `<a href="${values[values.length - 1]}">${strings[strings.length - 2]}</a>`;
        let formattedText: string = '<p>';
        for (let i = 0; i < values.length - 1; i++) {
            formattedText += `${strings[i]}${values[i]}`;
        }
        formattedText += `${policyTermsUrlText}</p>`;
        return formattedText;
    }
}

Elemento en el sitio web:

Elemento inspeccionado:

Fragmento de código

class StringElementConverter {
    constructor() {
        this.domParser = new DOMParser();
    }

    toElement(xmlString) {
        const parsedString = this.domParser.parseFromString(xmlString, 'text/xml').firstElementChild;
        if (parsedString == null) {
            throw new Error(`This xml string ${xmlString} is not parsable to Node`);
        }
        return parsedString;
    }
}

const template = `
<footer>
  <slot name="prepend"></slot>
  <slot name="center"></slot>
  <slot name="append"></slot>
</footer>
`;

class AppFooter extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = template;
        this.getElementsReferences();
        this.setCopyright({
            year: '2020',
            author: 'Krzysztof Kaczyński',
            termsReferenceUrl: 'https://www.google.com',
        });
    }

    getElementsReferences() {
        this.footer = this.shadowRoot.querySelector('footer');
    }

    setCopyright({ year, author, termsReferenceUrl }) {
        const copyrightText = this.formattedCopyrights`Copyright © ${year} ${author}. Policy terms${termsReferenceUrl}`;
        this.footer.appendChild(new StringElementConverter().toElement(copyrightText));
    }

    formattedCopyrights(strings, ...values) {
        const policyTermsUrlText = `<a href="${values[values.length - 1]}">${strings[strings.length - 2]}</a>`;
        let formattedText = '<p>';
        for (let i = 0; i < values.length - 1; i++) {
            formattedText += `${strings[i]}${values[i]}`;
        }
        formattedText += `${policyTermsUrlText}</p>`;
        return formattedText;
    }
}
customElements.define('kk-app-footer', AppFooter);
<kk-app-footer></kk-app-footer>

Si necesitas algo más, avísame en los comentarios

Respuesta #1

this.domParser.parseFromString(xmlString, 'text/xml')

No estás analizando tu contenido como el tipo de contenido correcto. Quieres:

this.domParser.parseFromString(xmlString, 'text/html')

Supongo que cuando analizas el contenido como XML en lugar de HTML, el navegador no cree que <a> tenga algún significado especial.


Ejemplo práctico:

class StringElementConverter {
    constructor() {
        this.domParser = new DOMParser();
    }

    toElement(xmlString) {
        const parsedString = this.domParser.parseFromString(xmlString, 'text/html').firstElementChild;
        if (parsedString == null) {
            throw new Error(`This xml string ${xmlString} is not parsable to Node`);
        }
        return parsedString;
    }
}

const template = `
<footer>
  <slot name="prepend"></slot>
  <slot name="center"></slot>
  <slot name="append"></slot>
</footer>
`;

class AppFooter extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = template;
        this.getElementsReferences();
        this.setCopyright({
            year: '2020',
            author: 'Krzysztof Kaczyński',
            termsReferenceUrl: 'https://www.google.com',
        });
    }

    getElementsReferences() {
        this.footer = this.shadowRoot.querySelector('footer');
    }

    setCopyright({ year, author, termsReferenceUrl }) {
        const copyrightText = this.formattedCopyrights`Copyright © ${year} ${author}. Policy terms${termsReferenceUrl}`;
        this.footer.appendChild(new StringElementConverter().toElement(copyrightText));
    }

    formattedCopyrights(strings, ...values) {
        const policyTermsUrlText = `<a href="${values[values.length - 1]}">${strings[strings.length - 2]}</a>`;
        let formattedText = '<p>';
        for (let i = 0; i < values.length - 1; i++) {
            formattedText += `${strings[i]}${values[i]}`;
        }
        formattedText += `${policyTermsUrlText}</p>`;
        return formattedText;
    }
}
customElements.define('kk-app-footer', AppFooter);
<kk-app-footer></kk-app-footer>