how can I add
<a href="javascript:function foo(){alert('hi');}" title="alert">
Drag to your bookmarks bar
</a>
in my wordpress post.
I have built a bookmarklet and i want to pass it through my blog. But wordpress is stripping out the javascript from my post when it displays it.
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:
- 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>
- Install a Custom Javascript Plugin. I used Simple Custom CSS and JS
- 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