Javascript in a wordpress post

三世轮回 提交于 2019-12-04 06:04:42

I have no issues embedding that code in the HTML editor on my wordpress site. There is a problem with your javascript code- that defines a function, but never calls it. I have

<a href="javascript:alert('hi');" title="alert">Drag to your bookmarks bar</a>

in a post, and I get the alert when click, as well as the bookmarklet.

The issue is likely to be caused at the browser end. Chrome's XSS was the problem for me and I solved it by adding the line header ("X-XSS-Protection: 0"); to wp-blog-header.php in the root folder of my installation. This may not be ideal as it applies across the whole site. It would probably be better to add it where it would only apply to the post/page which needs to render the bookmarklet.

This is old, but still relevant with Version 4.9.5 for wordpress, so I answer with my solution for this:

Wordpress filters out any Javascript you use in your Posts or pages, that is why your code gets lost. I did the following steps to add a "javascript:" Link:

  1. Add the Link you want to your post, use "#" as the href and add a id to the tag (in Text-Mode of the Editor):
<a href="#" id="idOfYourLink">This is my JS Link</a>
  1. Install a Custom Javascript Plugin. I used Simple Custom CSS and JS
  2. Add the Javascript you want with help from the plugin:
jQuery(document).ready(function( $ ){
  function yourFunction() {
      alert("It works");
  }

  jQuery('#idOfYourLink').on("click", yourFunction);
});

The important part is adding the on-Handler to the Link you want to use. Now the Javascript is loaded right after the page got loaded. And a click on the link will call the function yourFunction

Javascript in WordPress Single Pages and Posts

<script type="text/javascript">
<!--
// your code
//--></script>

Source: https://codex.wordpress.org/Using_Javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!