Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

<script> tag contents are not ignored #98

Open
dplarina opened this issue Sep 29, 2020 · 1 comment
Open

<script> tag contents are not ignored #98

dplarina opened this issue Sep 29, 2020 · 1 comment

Comments

@dplarina
Copy link

dplarina commented Sep 29, 2020

<script type="text/javascript">
  var link = "https://github.com/alexcorvi/anchorme.js/issues/new";
</script>

Results in the following html

<script type="text/javascript">
  var link = "<a href="https://stackoverflow.com/questions/31944794/how-to-enable-htmlmixed-mode-by-codemirror">https://stackoverflow.com/questions/31944794/how-to-enable-htmlmixed-mode-by-codemirror</a>";
</script>
@dplarina
Copy link
Author

My clunky workaround for this problem was to parse the input as html using a div tag, replace the contents of the script tags with a token before passing them through anchorme, and then restore them afterwards.

There's probably a better way, but this works.

// use a div element to parse the html
const parser = document.createElement('div');
parser.innerHTML = input;

const originalScripts = [];
// find all script tags in the html
let scriptTags = parser.getElementsByTagName('script');
for (var i = 0; i < scriptTags.length; i++) {
  // store the script contents for later
  originalScripts.push(scriptTags[i].innerText);
  // replace script contents with a temporary token
  scriptTags[i].innerText = `{{script-${i}}}`;
}

// convert anchors
var convertedHtml = anchorme(parser.innerHTML);

// restore script tag contents by replacing tokens with original value
for (var i = 0; i < originalScripts.length; i++) {
  convertedHtml = convertedHtml.replace(`{{script-${i}}}`, originalScripts[i]);
}

return convertedHtml;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant