无法使用书签运行外部JavaScript [英] unable to run an external javascript using a bookmarklet

查看:124
本文介绍了无法使用书签运行外部JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于JS的新手。

我需要使用外部脚本修改当前页面中的一些元素,将其作为书签进行访问。

I need to use an external script which modifies some elements in the current page accessing it as a bookmarklet.

如果我修改网页的html源代码,插入以下< script> lines:

If I modify the html source code of the web page inserting the following < script > lines:

s=document.createElement('script');
s.type='text/javascript';
s.src='script.js';
document.getElementsByTagName('head')[0].appendChild(s);

它运作正常。但是,如果我创建一个具有相同行的javascript:bookmarklet,我将获得一个包含以下字符串的空白页:

it works fine. But if I create a javascript: bookmarklet with the same lines, I obtain a blank page with the following string:

[object HTMLScriptElement]

然而,如果我创建一个添加行的书签

whereas, if I create a bookmarklet adding the line

void(null);

以前的网页,网页没有消失,但脚本没有执行。

to previous ones, the web page does not disapper but the script is not executed.

为什么?

推荐答案

通常的做法是简单地使用自动执行功能表达式,如下所示:

A common practice is to simply use a self-executing function expression, something like this:

(function () {
  var s=document.createElement('script');
  s.type='text/javascript';
  s.src='script.js';
  document.getElementsByTagName('head')[0].appendChild(s);
}());

Bookmarklet:

Bookmarklet:

javascript:(function(){var s=document.createElement('script');s.type='text/javascript';s.src='script.js';document.getElementsByTagName('head')[0].appendChild(s);}());

该函数将返回 undefined (不返回提供的值)阻止导航。

The function will return undefined (no return value supplied) preventing the navigation.

另请注意,这将避免创建可以创建的全局变量(如 s )与页面上使用的其他变量重叠,因为所有变量都是在匿名函数的范围内创建的。

Note also that this will avoid creating global variables (like s) that can overlap with other variables used on the page, because all variables are created in the scope of the anonymous function.

这篇关于无法使用书签运行外部JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆