Cybey
Cybey

Reputation: 71

Load external JS that has document.write in Angular2

In my current project we're looking to get a table from an external javascript file that contains a document.write. In the past we've done that in this fashion:

<script src="http://url.to.external.domain.com/file.ashx?sid=<ID>" type="text/javascript"></script>

This returns a javascript file that contains a single document.write() with the HTML that needs to be shown at the location of the script-tag.

We are now trying to do this in Angular2. In Angular1 I've managed to this by using a directive that writes the script tag into the template. This works fine.

Angular2 removes script tags from templates, so that is not a solution. I've tried creating a separate component to "mimic" the solution I used in Angular1 like this:

import { Component, Input } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'external-table',
    template: `<script src="http://url.to.external.domain.com/file.ashx?sid={{id}}" type="text/javascript"></script>`
})

export class ExternalTableComponent {
    @Input('id') id: number;
}

This raises a warning in the browser console:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Since I do not have access to this third-party server, I cannot change the way this table is generated or retrieved.

Does anyone have an idea on how I should do this in Angular2?

Upvotes: 1

Views: 1506

Answers (1)

Mark Lancaster
Mark Lancaster

Reputation: 214

Here's an example of loading the DarkSky API in Angular 7 with PostScribe after "npm install --save postscribe"

import postscribe from 'postscribe';

const script = '<script src="https://darksky.net/map-embed/@radar,41.88,-87.62,10.js?embed=true&timeControl=false&fieldControl=false&defaultField=radar"></script>';

postscribe('#darkSky', script);

Where there's a DIV in the template with ID of "darkSky"

Upvotes: 2

Related Questions