Javascript works as bookmarklet but not as onclick link

匆匆过客 提交于 2019-12-13 00:46:53

问题


I use the following code to allow users to add a bookmarklet to browsers, which works perfectly, but if I try actually firing the code from a link on a page it does not.

Is there something different I need to add/subtract from the code.

Here's what i use:

javascript:(function(d){
var%20modal=document.createElement('iframe');
modal.setAttribute('src','http://url.com/bm.html?
url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);
modal.setAttribute('scrolling','no');
modal.setAttribute('name','my_modal');
modal.className='modal';
document.body.appendChild(modal);
var%20c=document.createElement('link');
c.type='text/css';
c.rel='stylesheet';
c.href='//iframe.css';
document.body.appendChild(c);}(document));

I tried the following but doesn't work:

<a href="#" onclick="javascript:(function(d){var%20modal=document.createElement('iframe');modal.setAttribute('src','http://url.com/bm.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);modal.setAttribute('scrolling','no');modal.setAttribute('name','my_modal');modal.className='modal';document.body.appendChild(modal);var%20c=document.createElement('link');c.type='text/css';c.rel='stylesheet';c.href='//iframe.css';document.body.appendChild(c);}(document));">test</a>

回答1:


You have to:

  • replace %20 by space
  • remove javascript:

You could also use this function invocation trick !function( ...

Try this:

<a href="#" onclick="!function(d){var modal=document.createElement('iframe');modal.setAttribute('src','http://url.com/bm.html?url='+encodeURIComponent(window.location.href)+'&page_title='+document.title);modal.setAttribute('scrolling','no');modal.setAttribute('name','my_modal');modal.className='modal';document.body.appendChild(modal);var c=document.createElement('link');c.type='text/css';c.rel='stylesheet';c.href='//iframe.css';document.body.appendChild(c);}(document)">test</a>


来源:https://stackoverflow.com/questions/12008841/javascript-works-as-bookmarklet-but-not-as-onclick-link

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