重写内容

时间:2016-10-08 14:37:12

标签: javascript greasemonkey

我想使用Greasemonkey重写func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return muteForPickerData.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return muteForPickerData[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { } 内容。

我试过了:

<html>

不工作。

document.open() document.write(html) document.close() 仅替换内容。

一些建议?

1 个答案:

答案 0 :(得分:2)

不要使用document.write()。它有各种安全限制(由于坏人滥用)并且是fraught with pitfalls

如果您尝试使用它,就像在您的问题中一样,在用户脚本中; Firefox通常会完全停止页面或进入永久Connecting...然后重新加载周期 - 具体取决于脚本何时触发以及您是否使用unsafeWindow.stop()。 这种代码仍然适用于Chrome(目前),但仍然是一种不好的做法。不确定其他浏览器。

正确的方法是使用DOM方法。例如:

var D       = document;
var newDoc  = D.implementation.createHTMLDocument ("My new page title");
window.content = newDoc;

D.replaceChild (
    D.importNode (newDoc.documentElement, true),
    D.documentElement
);

D.body.innerHTML = '<h1>Standby...</h1>';

为了提高性能,您可能还希望使用:

// @run-at      document-start
// @grant       unsafeWindow

然后将unsafeWindow.stop ();放在用户代码的顶部。

回复:"How do I rewrite the head content with this solution?"

此示例已重写<head>。新的负责人将是:

<head><title>My new page title</title></head>

在这种情况下。

要添加其他头元素,请使用以下DOM代码:

var newNode     = D.createElement ('base');
newNode.href    = "http://www.example.com/dir1/page.html";
var targ        = D.getElementsByTagName ('head')[0];
targ.appendChild (newNode);

<强>除

  1. 只需使用GM_addStyle()即可轻松创建<style>个节点。
  2. 在您的方案中添加<script>节点几乎总是毫无意义。只需让您的用户脚本执行任何所需的JS处理。
  3. 会添加一些像<meta>这样的标签但不会被处理(特别是在Firefox中)。根据参数,这些仅在服务器的初始加载时进行解析。