最終更新: 2026-07-29
対象バージョン: BlinkGTK v1.1.0 以降
レベル: 初級〜中級
言語: 日本語 |
このチュートリアルでは、PythonとPyGObjectを使用してBlinkGTKのSettings APIを活用する方法を学びます。
Fedora/RHEL系:
sudo dnf install python3-gobject gtk4Ubuntu/Debian系:
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-4.0Arch Linux:
sudo pacman -S python-gobject gtk4#!/usr/bin/env python3
"""最小限のBlinkGTKアプリケーション"""
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
def on_activate(app):
"""アプリケーション起動時のコールバック"""
window = Gtk.ApplicationWindow(application=app)
window.set_title("My First BlinkGTK App")
window.set_default_size(800, 600)
web_view = blink_gtk.WebView.new()
window.set_child(web_view)
web_view.load_uri("https://example.com")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.first')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()実行:
python3 first_app.py#!/usr/bin/env python3
"""JavaScript制御の例"""
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
def on_activate(app):
window = Gtk.ApplicationWindow(application=app)
window.set_title("JavaScript Control")
window.set_default_size(800, 600)
web_view = blink_gtk.WebView.new()
window.set_child(web_view)
# JavaScript無効化
web_view.set_enable_javascript(False)
# 確認
js_enabled = web_view.get_enable_javascript()
print(f"JavaScript: {'有効' if js_enabled else '無効'}")
web_view.load_uri("https://example.com")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.jscontrol')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()#!/usr/bin/env python3
"""User-Agent変更の例"""
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
def on_activate(app):
window = Gtk.ApplicationWindow(application=app)
web_view = blink_gtk.WebView.new()
window.set_child(web_view)
# User-Agent変更
custom_ua = "MyPythonApp/1.0 (BlinkGTK; Python 3.11)"
web_view.set_user_agent(custom_ua)
# 確認
current_ua = web_view.get_user_agent()
print(f"User-Agent: {current_ua}")
web_view.load_uri("https://example.com")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.useragent')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()# JavaScript有効化
web_view.set_enable_javascript(True)
# JavaScript無効化
web_view.set_enable_javascript(False)js_enabled = web_view.get_enable_javascript()
print(f"JavaScript: {'有効' if js_enabled else '無効'}")デフォルト値: True(有効)
# モバイルエミュレーション
mobile_ua = "Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36"
web_view.set_user_agent(mobile_ua)
# カスタムUser-Agent
custom_ua = f"MyApp/{version} (BlinkGTK; Python {sys.version_info.major}.{sys.version_info.minor})"
web_view.set_user_agent(custom_ua)current_ua = web_view.get_user_agent()
print(f"現在のUser-Agent: {current_ua}")# 画像読み込み無効化(データセーバーモード)
web_view.set_auto_load_images(False)
# 画像読み込み有効化
web_view.set_auto_load_images(True)images_enabled = web_view.get_auto_load_images()
print(f"画像読み込み: {'有効' if images_enabled else '無効'}")デフォルト値: True(有効)
# ローカルストレージ無効化(プライバシーモード)
web_view.set_enable_local_storage(False)
# ローカルストレージ有効化
web_view.set_enable_local_storage(True)storage_enabled = web_view.get_enable_local_storage()
print(f"ローカルストレージ: {'有効' if storage_enabled else '無効'}")デフォルト値: True(有効)
from typing import Optional
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
class BrowserSettings:
"""ブラウザ設定を管理するクラス"""
def __init__(self, web_view: blink_gtk.WebView):
self.web_view = web_view
def enable_javascript(self, enabled: bool) -> None:
"""JavaScriptを有効/無効にする"""
self.web_view.set_enable_javascript(enabled)
def set_user_agent(self, user_agent: str) -> None:
"""User-Agentを設定する"""
self.web_view.set_user_agent(user_agent)
def enable_images(self, enabled: bool) -> None:
"""画像読み込みを有効/無効にする"""
self.web_view.set_auto_load_images(enabled)
def enable_storage(self, enabled: bool) -> None:
"""ローカルストレージを有効/無効にする"""
self.web_view.set_enable_local_storage(enabled)
def get_settings(self) -> dict[str, any]:
"""現在の設定を辞書で取得"""
return {
'javascript': self.web_view.get_enable_javascript(),
'images': self.web_view.get_auto_load_images(),
'storage': self.web_view.get_enable_local_storage(),
'user_agent': self.web_view.get_user_agent(),
}
def apply_settings(self, settings: dict[str, any]) -> None:
"""設定を一括適用"""
if 'javascript' in settings:
self.enable_javascript(settings['javascript'])
if 'images' in settings:
self.enable_images(settings['images'])
if 'storage' in settings:
self.enable_storage(settings['storage'])
if 'user_agent' in settings:
self.set_user_agent(settings['user_agent'])class BrowserWindow(Gtk.ApplicationWindow):
"""プロパティを使用したブラウザウィンドウ"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._web_view = blink_gtk.WebView.new()
self.set_child(self._web_view)
@property
def javascript_enabled(self) -> bool:
"""JavaScriptが有効かどうか"""
return self._web_view.get_enable_javascript()
@javascript_enabled.setter
def javascript_enabled(self, enabled: bool) -> None:
"""JavaScriptを有効/無効にする"""
self._web_view.set_enable_javascript(enabled)
@property
def user_agent(self) -> str:
"""現在のUser-Agent"""
return self._web_view.get_user_agent()
@user_agent.setter
def user_agent(self, ua: str) -> None:
"""User-Agentを設定"""
self._web_view.set_user_agent(ua)
@property
def images_enabled(self) -> bool:
"""画像読み込みが有効かどうか"""
return self._web_view.get_auto_load_images()
@images_enabled.setter
def images_enabled(self, enabled: bool) -> None:
"""画像読み込みを有効/無効にする"""
self._web_view.set_auto_load_images(enabled)
# 使用例
window = BrowserWindow(application=app)
# プロパティとして使用
window.javascript_enabled = False
window.user_agent = "MyApp/1.0"
window.images_enabled = False
print(f"JavaScript: {window.javascript_enabled}")
print(f"User-Agent: {window.user_agent}")from contextlib import contextmanager
from typing import Iterator
@contextmanager
def temporary_settings(
web_view: blink_gtk.WebView,
**settings
) -> Iterator[None]:
"""
一時的に設定を変更するコンテキストマネージャ
使用例:
with temporary_settings(web_view, javascript=False, images=False):
web_view.load_uri("https://example.com")
# コンテキスト終了後、元の設定に自動復帰
"""
# 現在の設定を保存
original = {
'javascript': web_view.get_enable_javascript(),
'images': web_view.get_auto_load_images(),
'storage': web_view.get_enable_local_storage(),
}
# 新しい設定を適用
if 'javascript' in settings:
web_view.set_enable_javascript(settings['javascript'])
if 'images' in settings:
web_view.set_auto_load_images(settings['images'])
if 'storage' in settings:
web_view.set_enable_local_storage(settings['storage'])
try:
yield
finally:
# 元の設定に戻す
web_view.set_enable_javascript(original['javascript'])
web_view.set_auto_load_images(original['images'])
web_view.set_enable_local_storage(original['storage'])
# 使用例
with temporary_settings(web_view, javascript=False, images=False):
# このブロック内では設定が変更される
web_view.load_uri("https://example.com")
# ブロック終了後、自動的に元の設定に戻るfrom dataclasses import dataclass
@dataclass
class BrowserConfig:
"""ブラウザ設定を表すデータクラス"""
javascript: bool = True
images: bool = True
storage: bool = True
user_agent: str = ""
def apply_to(self, web_view: blink_gtk.WebView) -> None:
"""WebViewに設定を適用"""
web_view.set_enable_javascript(self.javascript)
web_view.set_auto_load_images(self.images)
web_view.set_enable_local_storage(self.storage)
if self.user_agent:
web_view.set_user_agent(self.user_agent)
@classmethod
def from_web_view(cls, web_view: blink_gtk.WebView) -> 'BrowserConfig':
"""WebViewから現在の設定を取得"""
return cls(
javascript=web_view.get_enable_javascript(),
images=web_view.get_auto_load_images(),
storage=web_view.get_enable_local_storage(),
user_agent=web_view.get_user_agent(),
)
# 使用例
# プリセット定義
DATA_SAVER = BrowserConfig(javascript=False, images=False)
PRIVACY_MODE = BrowserConfig(javascript=False, images=False, storage=False)
NORMAL_MODE = BrowserConfig()
# 適用
DATA_SAVER.apply_to(web_view)
# 現在の設定を取得
current_config = BrowserConfig.from_web_view(web_view)
print(f"JavaScript: {current_config.javascript}")#!/usr/bin/env python3
"""データセーバーモードの実装"""
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
class DataSaverBrowser(Gtk.ApplicationWindow):
"""データセーバーモード付きブラウザ"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_title("Data Saver Browser")
self.set_default_size(800, 600)
# UI構築
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# データセーバースイッチ
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
hbox.set_margin_start(10)
hbox.set_margin_end(10)
hbox.set_margin_top(10)
hbox.set_margin_bottom(10)
label = Gtk.Label(label="データセーバーモード:")
self.data_saver_switch = Gtk.Switch()
self.data_saver_switch.connect('notify::active', self.on_data_saver_toggled)
hbox.append(label)
hbox.append(self.data_saver_switch)
# WebView
self.web_view = blink_gtk.WebView.new()
vbox.append(hbox)
vbox.append(self.web_view)
self.web_view.set_vexpand(True)
self.set_child(vbox)
def on_data_saver_toggled(self, switch, _):
"""データセーバーモード切り替え"""
enabled = switch.get_active()
if enabled:
# データセーバーモード有効
self.web_view.set_enable_javascript(False)
self.web_view.set_auto_load_images(False)
print("データセーバーモード: 有効")
else:
# 通常モード
self.web_view.set_enable_javascript(True)
self.web_view.set_auto_load_images(True)
print("データセーバーモード: 無効")
def on_activate(app):
window = DataSaverBrowser(application=app)
window.web_view.load_uri("https://www.chromium.org")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.datasaver')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()#!/usr/bin/env python3
"""設定パネル付きブラウザ"""
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
class SettingsPanel(Gtk.Box):
"""設定パネルウィジェット"""
def __init__(self, web_view: blink_gtk.WebView):
super().__init__(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
self.web_view = web_view
self.set_margin_start(10)
self.set_margin_end(10)
self.set_margin_top(10)
self.set_margin_bottom(10)
# JavaScript
self.append(Gtk.Label(label="JavaScript:"))
self.js_switch = Gtk.Switch()
self.js_switch.set_active(True)
self.js_switch.connect('notify::active',
lambda s, _: web_view.set_enable_javascript(s.get_active()))
self.append(self.js_switch)
# 画像
self.append(Gtk.Label(label="画像:"))
self.images_switch = Gtk.Switch()
self.images_switch.set_active(True)
self.images_switch.connect('notify::active',
lambda s, _: web_view.set_auto_load_images(s.get_active()))
self.append(self.images_switch)
# ストレージ
self.append(Gtk.Label(label="ストレージ:"))
self.storage_switch = Gtk.Switch()
self.storage_switch.set_active(True)
self.storage_switch.connect('notify::active',
lambda s, _: web_view.set_enable_local_storage(s.get_active()))
self.append(self.storage_switch)
class BrowserWindow(Gtk.ApplicationWindow):
"""設定パネル付きブラウザウィンドウ"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_title("Browser with Settings")
self.set_default_size(1000, 700)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# WebView
self.web_view = blink_gtk.WebView.new()
# 設定パネル
self.settings_panel = SettingsPanel(self.web_view)
vbox.append(self.settings_panel)
vbox.append(self.web_view)
self.web_view.set_vexpand(True)
self.set_child(vbox)
def on_activate(app):
window = BrowserWindow(application=app)
window.web_view.load_uri("https://www.chromium.org")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.settings')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()#!/usr/bin/env python3
"""プロファイルシステムの実装"""
from dataclasses import dataclass
from enum import Enum
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk
import blink_gtk
class ProfileType(Enum):
"""プロファイルタイプ"""
NORMAL = "通常"
DATA_SAVER = "データセーバー"
PRIVACY = "プライバシー"
MOBILE = "モバイル"
@dataclass
class BrowserProfile:
"""ブラウザプロファイル"""
name: str
javascript: bool
images: bool
storage: bool
user_agent: str = ""
def apply_to(self, web_view: blink_gtk.WebView) -> None:
"""プロファイルを適用"""
web_view.set_enable_javascript(self.javascript)
web_view.set_auto_load_images(self.images)
web_view.set_enable_local_storage(self.storage)
if self.user_agent:
web_view.set_user_agent(self.user_agent)
# プロファイル定義
PROFILES = {
ProfileType.NORMAL: BrowserProfile(
name="通常モード",
javascript=True,
images=True,
storage=True,
),
ProfileType.DATA_SAVER: BrowserProfile(
name="データセーバーモード",
javascript=False,
images=False,
storage=True,
),
ProfileType.PRIVACY: BrowserProfile(
name="プライバシーモード",
javascript=False,
images=False,
storage=False,
),
ProfileType.MOBILE: BrowserProfile(
name="モバイルエミュレーション",
javascript=True,
images=True,
storage=True,
user_agent="Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36",
),
}
class ProfileBrowser(Gtk.ApplicationWindow):
"""プロファイル切り替え可能なブラウザ"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.set_title("Profile Browser")
self.set_default_size(1000, 700)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# プロファイル選択
hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
hbox.set_margin_start(10)
hbox.set_margin_end(10)
hbox.set_margin_top(10)
hbox.append(Gtk.Label(label="プロファイル:"))
self.profile_combo = Gtk.ComboBoxText()
for profile_type in ProfileType:
self.profile_combo.append(profile_type.value, profile_type.value)
self.profile_combo.set_active(0)
self.profile_combo.connect('changed', self.on_profile_changed)
hbox.append(self.profile_combo)
# WebView
self.web_view = blink_gtk.WebView.new()
vbox.append(hbox)
vbox.append(self.web_view)
self.web_view.set_vexpand(True)
self.set_child(vbox)
def on_profile_changed(self, combo):
"""プロファイル変更時"""
profile_name = combo.get_active_text()
# プロファイルを検索
for profile_type, profile in PROFILES.items():
if profile.name == profile_name:
profile.apply_to(self.web_view)
print(f"プロファイル適用: {profile.name}")
break
def on_activate(app):
window = ProfileBrowser(application=app)
window.web_view.load_uri("https://www.chromium.org")
window.present()
if __name__ == '__main__':
blink_gtk.init()
app = Gtk.Application(application_id='org.example.profiles')
app.connect('activate', on_activate)
app.run()
blink_gtk.shutdown()| WebKitGTK (Python) | BlinkGTK (Python) | 互換性 |
|---|---|---|
settings.set_enable_javascript(enabled) |
web_view.set_enable_javascript(enabled) |
対応 |
settings.get_enable_javascript() |
web_view.get_enable_javascript() |
対応 |
settings.set_user_agent(ua) |
web_view.set_user_agent(ua) |
対応 |
settings.get_user_agent() |
web_view.get_user_agent() |
対応 |
settings.set_auto_load_images(enabled) |
web_view.set_auto_load_images(enabled) |
対応 |
settings.get_auto_load_images() |
web_view.get_auto_load_images() |
対応 |
settings.set_enable_local_storage(enabled) |
web_view.set_enable_local_storage(enabled) |
対応 |
settings.get_enable_local_storage() |
web_view.get_enable_local_storage() |
対応 |
Before (WebKitGTK):
import gi
gi.require_version('WebKit2', '4.1')
from gi.repository import WebKit2
web_view = WebKit2.WebView()
settings = web_view.get_settings()
settings.set_enable_javascript(False)
settings.set_user_agent("MyApp/1.0")After (BlinkGTK):
import blink_gtk
web_view = blink_gtk.WebView.new()
# Settingsオブジェクト不要、直接WebViewに設定
web_view.set_enable_javascript(False)
web_view.set_user_agent("MyApp/1.0")主な違い:
このチュートリアルでは、Python/PyGObjectでBlinkGTK Settings APIを使用する方法を学びました。
作成者: BlinkGTK開発チーム
ライセンス: BSD 3-Clause
フィードバック: daisy19@gmail.com